Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

MergeSort function in java displaying zeroes

I followed a tutorial on mergesort algoorithm in java and it displayed 0000002468 as result.

I gave input of number from 1,2,3…9,0.
It was supposed to sort in ascending order.
I double checked with the tutorial also and found nothing wrong.
I can’t solve it myself since i didn’t really understand.
Tutorial is by BroCode btw.

Code:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

class m{
    public static void main(String[]args){
        int array[] = {8,4,5,3,2,7,1,9,0,6};

        mergeSort(array);
    
    for(int i =0;i<array.length;i++){
        System.out.print(array[i] + "");

    }

}
private static void mergeSort(int[]array){

    int length = array.length;
    if(length<=1)return;//base case
    int middle = length/2;
    int leftArray[] = new int[middle];
    int rightArray[] = new int[length-middle];
    int i=0;//left array
    int j = 0;//right array
    for(;i<length;i++){
        if(i<middle){
            leftArray[i] = array[i];

        }else{
            rightArray[j] = array[i];
        }
    }mergeSort(leftArray);
     mergeSort(rightArray);
     merge(leftArray,rightArray,array);

    }

    private static void merge(int[]leftArray,int[]rightArray,int[]array){
        int leftSize = array.length/2;
        int rightSize = array.length-leftSize;
        int i=0,l=0,r=0;

        // check conditions for merging

        while(l<leftSize && r<rightSize){
            if(leftArray[l]<rightArray[r]){
                array[i] = leftArray[l];
                i++;
                l++;
            }else{
                array[i] = rightArray[r];
                i++;
                r++;
            }
        }
        while(l<leftSize){
            array[i] = leftArray[l];
            i++;
            l++;

        }
        while(r<rightSize){
            array[i] = rightArray[r];
            i++;
            r++;
        }
    }

}

>Solution :

You forgot to increment your j index while breaking down the original array into 2.

else{
     rightArray[j++] = array[i];
}

In your code, you are just setting and replacing again and again the first element of the array, rightArray.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading