Just writing some basic mergeSort code and I can't figure out if there is something wrong with my logic. To me it should work fine.
So, ideally it should print out elements in sorted order: 1 2 8 11 17 19 25 50.
But the output displayed is: 8 2 11 1 17 19 25 50
I am not getting what's wrong with this code. Am I going wrong with the logic?
If somebody can help me out it would be great. Sorry if this is a very silly question to ask here.
public class MergeSort
{
static final int arr[] = {8, 2, 19, 25, 11, 1, 17, 50};
static int sorted[] = new int[arr.length];
public static void main(String args[])
{
mergeSort(0, arr.length - 1);
display();
}
static void display()
{
for(int i=0; i<sorted.length; i++)
{
System.out.print(sorted[i] + " ");
}
}
static void mergeSort(int first, int last)
{
if(first < last)
{
int mid = (first + last)/2;
mergeSort(first, mid);
mergeSort(mid + 1, last);
merge(first, mid, last);
}
}
static void merge(int first, int mid, int last)
{
int ansIndex = 0;
int index1 = first;
int index2 = mid + 1;
while(index1 <= mid && index2 <= last)
if(arr[index1] < arr[index2])
{
sorted[ansIndex] = arr[index1];
index1++;
ansIndex++;
}
else if(arr[index2] < arr[index1])
{
sorted[ansIndex] = arr[index2];
index2++;
ansIndex++;
}
else
{
sorted[ansIndex] = arr[index1];
index1++; index2++; ansIndex++;
}
if(index1 <= mid)
while(index1 <= mid)
{
sorted[ansIndex] = arr[index1];
ansIndex++; index1++;
}
else if(index2 <= last)
while(index2 <= last)
{
sorted[ansIndex] = arr[index2];
index2++; ansIndex++;
}
}
}