简体   繁体   English

合并排序不排序数组

[英]merge sort not sorting array

I have written the Java code below after reading up on merge sort. 阅读合并排序后,我已经在下面编写了Java代码。 There are no errors when running the code but the merge sort does not sort the array. 运行代码时没有错误,但是合并排序不会对数组进行排序。 It just returns the original unsorted array. 它只是返回原始的未排序数组。 I can't for the life of me figure out where the problem might be. 我一生无法弄清楚问题可能出在哪里。 I appreciate any leads. 我感谢任何线索。

public class mergeSort {

public void mergeSort(int array[], int n){

    if(n<2) return; 
    int m=n/2;
    int left[]=new int[m];
    int right[]=new int[n-m];
    int i;

    for(i=0; i<m;i++){
        left[i]=array[i];
    }
    for( i=m; i<n;i++){
        right[i-m]=array[i];
    }
    printArray(left);
    printArray(right);
    mergeSort(left, m);
    mergeSort(right, n-m);
    merge(array, left, m, right, m-n);
}

private void merge(int[] array, int[] left, int leftCount, int[] right, int rightCount) {
    int i=0,j=0,k=0;

    while(i<leftCount && j< rightCount){
        if(left[i]<=right[j]){
            array[k]=left[i];
            i++;
            k++;
        }else{
            array[k]=right[j];
            j++;
            k++;
        }
    }

    while(i<leftCount){
        array[k]=left[i];
        i++;
        k++;
    }
    while(j<rightCount){
        array[k]=right[j];
        j++;
        k++;
    }

}
 static void printArray(int arr[])
    {
        int n = arr.length;
        for (int i=0; i<n; ++i)
            System.out.print(arr[i] + " ");
        System.out.println();
    }

public static void main(String[] args){
    int a[]={3,2,1,7,9,8};
    printArray(a);


    mergeSort m=new mergeSort();
    m.mergeSort(a, a.length);

    printArray(a);
}

} }

The leftCount and rightCount that you pass to the merge method is wrong. 您传递给merge方法的leftCount和rightCount错误。

Instead don't pass that but calculate that in the merge method. 相反,不要传递它,而是在merge方法中进行计算。 I tried your code with the below change and it works perfectly fine. 我用以下更改尝试了您的代码,它工作得很好。

 merge(array, left, right);
 ...
private void merge(int[] array, int[] left,  int[] right) {
    int i=0,j=0,k=0;
    int leftCount= left.length;
    int rightCount = right.length;

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

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