Newbie
Newbie

Reputation: 2708

Merge Sort Example

I am new to Java and I have tried writing a Merge Sort Program . MergeSort.java program is below :-

public class MergeSort {

    public static int b[] = {6,2,3,1,9};

    public void MergeSort(int a[],int left[], int right[]) {

        int i = 0,j = 0,k = 0;

        int l = left.length;

        int r = right.length;
        int v = a.length;

        while ( i < l && j < r) {
            if( left[i] < right[j]) {
                a[k] = left[i] ;
                i++;
            } else {
                a[k] = right [j];
                j++;
            }
            k++;
        }
        while ( i < l ) {
            a[k] = left[i];
            k++;
            i++;

        }
        while ( j < r ) {
            a[k] = right[j];
            k++;
            j++;

        }

    }

    public void Merge(int a[], int length) {


        int n = length;
        if(n < 2) return;
        int mid = n/2;

        int left[] = new int[mid];
        int right[] = new int[n-mid];
        for (int i = 0 ; i <mid ; i++) {
            left[i] = a[i];
        }
        for (int i = mid ; i <n ; i++) {
            right[i-mid] = a[i];
        }

        Merge(right,n-mid);
        Merge(left,mid);
        MergeSort(b, left, right);

    }

    public static void main(String[] args) {
        // TODO Auto-generated method stub


        MergeSort ms = new MergeSort();
        ms.Merge(b,b.length);
        for(int i=0 ; i < b.length ; i++)
        System.out.println(b[i]);

    }

}

When I run this program , the output I get is

3
1
6
2
9

But , the expected output is 1 2 3 6 9

Can anyone please help me point out the mistake I am doing and try to help me fix it please .I have tried debugging it on Eclipse but could not spot the bug . Thanks

Upvotes: 0

Views: 1078

Answers (1)

Michael Petch
Michael Petch

Reputation: 47573

Are you sure you meant this in function Merge:

MergeSort(b, left, right);

It seems it should be:

MergeSort(a, left, right);

Upvotes: 3

Related Questions