java - merge sort not sorting array -


i have written java code below after reading on merge sort. there no errors when running code merge sort not sort array. returns original unsorted array. can't life of me figure out problem might be. appreciate leads.

public class mergesort {  public void mergesort(int array[], int n){      if(n<2) return;      int m=n/2;     int left[]=new int[m];     int right[]=new int[n-m];     int i;      for(i=0; i<m;i++){         left[i]=array[i];     }     for( i=m; i<n;i++){         right[i-m]=array[i];     }     printarray(left);     printarray(right);     mergesort(left, m);     mergesort(right, n-m);     merge(array, left, m, right, m-n); }  private void merge(int[] array, int[] left, int leftcount, int[] right, int rightcount) {     int i=0,j=0,k=0;      while(i<leftcount && j< rightcount){         if(left[i]<=right[j]){             array[k]=left[i];             i++;             k++;         }else{             array[k]=right[j];             j++;             k++;         }     }      while(i<leftcount){         array[k]=left[i];         i++;         k++;     }     while(j<rightcount){         array[k]=right[j];         j++;         k++;     }  }  static void printarray(int arr[])     {         int n = arr.length;         (int i=0; i<n; ++i)             system.out.print(arr[i] + " ");         system.out.println();     }  public static void main(string[] args){     int a[]={3,2,1,7,9,8};     printarray(a);       mergesort m=new mergesort();     m.mergesort(a, a.length);      printarray(a); } 

}

the leftcount , rightcount pass merge method wrong.

instead don't pass calculate in merge method. tried code below change , works fine.

 merge(array, left, right);  ... private void merge(int[] array, int[] left,  int[] right) {     int i=0,j=0,k=0;     int leftcount= left.length;     int rightcount = right.length; 

Comments

Popular posts from this blog

android - InAppBilling registering BroadcastReceiver in AndroidManifest -

python Tkinter Capturing keyboard events save as one single string -

sql server - Why does Linq-to-SQL add unnecessary COUNT()? -