MergeSort好奇

时间:2013-02-02 03:46:25

标签: java algorithm mergesort

我一直在尝试实现我自己的“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]);
            }
        }
}

1 个答案:

答案 0 :(得分:2)

merge结束时,如果您要添加每个方面的剩余内容......您就不会增加counterNewArray。这导致将一堆值分配给一个点,相互覆盖......并使bigArray的尾部保留无效值(零,IIRC)。