The following is my implementation of merge sort.
private static void mergeSort(int[] a, int low , int high,int[] res)
{
int mid = (low + high) /2;
if (low < high)
{
mergeSort(a,low,mid-1,res);
mergeSort(a,mid,high-1,res);
merge(a,low,mid,high,res);
}
}
private static void merge(int[] a, int low , int mid , int high,int[] res)
{
int i = low;
int j = mid ;
int k =0;
while (i < mid && j < high)
if(a[i] < a[j])
res[k++] = a[i++];
else
res[k++] = a[j++];
while(i < mid)
res[k++] = a[i++];
while(j < high)
res[k++] =a[j++];
}
When I run this program in the main method, I get the original array printed. Not sure what the problem is. The merge method works when I test is individually though.
public static void main(String[] args)
{
int[] a = {45,24,53,13,54,45,63,23};
int[] res = new int[a.length];
mergeSort(a,0,a.length,res);
for(int i=0 ; i < res.length ; i++)
{
System.out.print(res[i] +",");
}
}
Output :
45,24,53,13,54,45,63,23,
I have spent a lot of time looking for the problem. I am not able to fix it.
The answer is as @Mysticial sais, with the exception that the array needs to be copied within the merge method:
At any rate, let it be noted that doing this will overwrite the original array… so you might want to wrap the call to mergeSort to avoid it:
Hope this helps!