0

我一直在尝试实现我的“自己的”MergeSort,它似乎适用于较小的值,但我正在以随机顺序在 1-100,000 的数组上尝试它,并在我打印回来时混合了一些奇怪的数字。我已经跟踪了 10 次,但没有运气。

public static void mergeSort(int[] array){
    if(array.length > 1){

       int midPoint = array.length/2; 

       int[] leftArray = new int[midPoint];
       int[] rightArray = new int[array.length - midPoint];

       System.arraycopy(array, 0, leftArray, 0, midPoint);
       System.arraycopy(array, midPoint, rightArray, 0, array.length - midPoint);

       mergeSort(leftArray);
       mergeSort(rightArray);

       merge(leftArray, rightArray, array);
    }
}

public static void merge(int[] left, int[] right, int[] bigArray){
    int counterLeft = 0, counterRight = 0, counterNewArray = 0;

    while(counterLeft < left.length && counterRight < right.length){
        if(left[counterLeft] < right[counterRight]){
            bigArray[counterNewArray] = left[counterLeft];
            counterLeft++;
            counterNewArray++;
        }else{
            bigArray[counterNewArray] = right[counterRight];
            counterRight++;
            counterNewArray++;
        }
    }

        while(counterLeft < left.length){
                bigArray[counterNewArray] = left[counterLeft];
                counterLeft++;
        }

        while(counterRight < right.length){
                bigArray[counterNewArray] = right[counterRight];
                counterRight++;
        }

        if(bigArray.length < 500){
            System.out.println("Merged array:");
            for(int i = 0; i < bigArray.length; i++){
                System.out.println(bigArray[i]);
            }
        }
}
4

1 回答 1

2

在结束时merge,当你添加每一边的剩余部分时......你没有增加counterNewArray. 这导致一堆值被分配到一个点,相互覆盖......并留下bigArray无效值(零,IIRC)的尾部。

于 2013-02-02T03:58:44.837 回答