简体   繁体   English

合并Java中的排序无法正常工作。 尝试不使用while循环

[英]Merge Sort in Java not working as expected. Trying to do it without a while loop

I've been working on this all day and have no idea why this isn't working. 我整天都在努力,不知道为什么这不起作用。 The sort is duplicating some elements and is sorting some of the array but I can't see what is causing this. 排序正在复制某些元素,并对数组进行了排序,但是我看不到是什么原因造成的。 Tried to trace it but couldn't follow it. 试图追踪它,但无法追踪。

import java.io.FileNotFoundException;
import java.util.Arrays;
public class Main {
    public static void main(String[] args) throws FileNotFoundException {

        int[] array = new int[10];
        for(int i = 0; i < array.length; i++) {
            array[i] = (int) (Math.random()*5);
        }

        int[] temp = array.clone();
        int l = 0;
        int r = array.length-1;
        System.out.println("unsorted "+Arrays.toString(array));
        mergeSort(array, temp, l, r);
        System.out.println("sorted "+Arrays.toString(array));
    }

    public static void mergeSort(int[] array, int[] temp, int p, int r) {
        int q = (p + r)/2;
        if(p < r) {
            mergeSort(array, temp, p, q);
            mergeSort(array, temp, q+1, r);
            merge(array, temp, p, q, r);
        }
    }

    public static void merge(int[] array, int[] temp, int p, int q, int r) {


        int i = p;
        int j = q + 1;

        for(int k = p; k < r; k++){
        if(i > q){
            array[k] = temp[j];
            j++;
        } else if(j > r) {
            array[k] = temp[i];
            i++;
        }  
        else if(temp[j] < temp[i]) {
            array[k] = temp[j];
            j++;
        } else {
            array[k] = temp[i];
            i++;
        }
      }
    }
}

Your code has two problems: 您的代码有两个问题:

  1. Your for loop should be inclusive of r as it is the last index: 您的for循环应包含r因为它是最后一个索引:

     for( int k = p; k <= r; k++ ) 
  2. You have to copy back to the temp at the end of your merge operation: 您必须在合并操作结束时复制回temp

     for ( int k = p; k <= r; k++ ) { temp[ k ] = array[ k ]; } 

    or: 要么:

     System.arraycopy( array, p, temp, p, r + 1 - p ); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM