Ristoph
Ristoph

Reputation: 37

MergeSort wonkiness

I've been trying to implement my "own" MergeSort and it seems to work for smaller values but I'm trying it on an array of 1-100,000 in random order and getting some strange numbers mixed in when I print it back out. I've tracked it like 10 times with no luck.

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]);
            }
        }
}

Upvotes: 0

Views: 103

Answers (1)

cHao
cHao

Reputation: 86506

At the end of merge, when you're adding what remains of each side...you're not incrementing counterNewArray. This leads to a bunch of values being assigned to one spot, overwriting each other...and leaving the tail of bigArray with invalid values (zeroes, IIRC).

Upvotes: 2

Related Questions