So I am trying to implement a MergeSort algorithm on an array.
My unsorted array is[3, -5, -10, 22, -100, 1]
However, when executed it is [-5, -10, 3, 22, -100, 1]
Clearly, the right side of the array position 4 and 5 aren't clearly merging.
I was thinking that maybe I haven't partitioned the array fully and that is why it isn't merging correctly.
Below is my mergeSort code:
public static void main(String[] args) {
// TODO Auto-generated method stub
int [] arr = {3, -5, -10, 22, -100, 1};
System.out.println("unsorted array is" +Arrays.toString(arr));
mergeSort(arr, 0, arr.length);
System.out.println("it is now merged "+ Arrays.toString(arr));
}
public static void mergeSort(int[] arr, int start, int end) {
// TODO Auto-generated method stub
if(end -start < 2) {
return;
}
int mid = (start + end)/2;
//merge the left side of array
mergeSort(arr, start, mid);
//merge the right side of the array
mergeSort(arr,mid +1, end);
merge(arr, start, mid, end);
}
public static void merge(int [] arr, int start, int mid, int end) {
//checking
if(arr[mid -1] <= arr[mid]) {
return;
}
if(start <= end && mid >= start && mid <= end) {
//creating temporary array
int [] temp = new int[end -start + 1];
//initialising values
int i = start;
int j = mid;
int tempIndex = 0;
while(i < mid && j < end + 1) {
if(arr[i] > arr[j]) {
temp[tempIndex] = arr[j];
j++;
}
else {
temp[tempIndex] = arr[i];
i ++;
}
tempIndex ++;
}
//exit while loop
if(i < mid) {
//if that is true then loop
for(; i< mid; i++) {
temp[tempIndex] = arr[i];
tempIndex ++;
}
}
else {
for(;j < end +1; j++) {
temp[tempIndex] = arr[j];
tempIndex ++;
}
}
//copy back into array
for (int k = start;k <= end; k++) {
arr[k] = temp[k-start];
}
}
}}
Correct two things: In main:
mergeSort(arr, 0, arr.length);
to:
mergeSort(arr, 0, arr.length-1);
and in mergeSort method
//merge the right side of the array
mergeSort(arr, mid+1, end);
to:
//merge the right side of the array
mergeSort(arr, mid, end);
The thing is that you always provide more elements that array has (elements are counted from 0 to arr.length-1) and than you omit last divide in recursive tree when elements in dividing array are even. (So you skip merge of right part of array)