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}
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.