-1

I am trying to implement the mergesort algorithm and I did what you see below, but I don't seem to get the right result, please check my code out and let me know what I am missing.

package test;

public class MergeSort {

  private static void mergesort(int[] arr, int n) {
      int mid;
      int[] left;
      int[] right;
      if(n<2 ){return;}
      mid = n/2;

      left = new int[mid];
      right = new int[n-mid];

      for(int i=0;i<mid;i++){
          left[i]=arr[i];

      }
      for(int i=mid;i<n;i++){
          right[i-mid]=arr[i];

      }

      mergesort(left,mid);
      mergesort(right,n-mid);
      merge(arr,left,mid,right,n-mid);

  }


private static void merge(int[] arr, int[] left, int leftcount, int[] right, int rightcount) {
    // TODO Auto-generated method stub
    int i,j,k;

    i=0;j=0;k=0;

    while(i<leftcount && j<rightcount){
        if(left[i] <right[i]){
            arr[k]=left[i];
            k++;
            i++;
        }
        else{
            arr[k]=right[j];
            k++;
            j++;

        }
    }

    //copy what left if any
    while(i<leftcount){
        arr[k]=left[i];
        k++;
        i++;
    }
    //copy whats left if any
    while(j<rightcount){
        arr[k]=right[j];
        k++;
        j++;
    }

}

public static void main(String[]args){

    int[] arr = {2,4,1,7,3};
    for(int i = 0;i<arr.length;i++){
        System.out.print(arr[i] + " ");
    }
    System.out.println();
    mergesort(arr,arr.length);
    for(int i = 0;i<arr.length;i++){
        System.out.println(arr[i] +" ");
    }       
  }
}

as you see my test array to sort is {2,4,1,7,3}; but i have this as my sorted array {1 3 7 2 4}

John Powell
  • 12,253
  • 6
  • 59
  • 67
user3137376
  • 1,527
  • 2
  • 19
  • 29
  • This is likely to be an off by one error. Put break points in the relevant places and check that your arrays are being split properly. – John Powell Jul 20 '14 at 08:35

1 Answers1

6

Your problem is at this line:

 if(left[i] <right[i]){

Suppose now you have two subsets: {2, 4} and {1, 3, 7}.

i = 0: right[i] < left[i] you get {1}

i = 1: right[i] < left[i] you get {1, 3} rather than {1, 2} that you want.

So your problem is the same index of left[] and right[].

Solution: change that line to

 if(left[i] <right[j]){

NOTE:Besides, learning to debug, that is a very important skill.

Tony
  • 5,972
  • 2
  • 39
  • 58