import java.util.Arrays;
public class mergeSort{
public static void main(String[] args) {
int[] arr = {2, 4, 5, 7, 1, 2, 3, 6};
int size = arr.length;
int[] L, R;
L = new int[size/2]; //setup both the left and right side arrays
R = new int[size/2];
int k, i = 0, j = 0;
for(k = 0; k < size; k++){
if (k < size/2){
L[i] = arr[k];
i++; //iterate through the left side
}
else{
R[j] = arr[k];
j++;// iterate through the right side
}
}
i = 0;
j = 0;
for (k = 0; k < size; k++){
if (i < L.length && j < R.length){
if(L[i] < R[j]){
arr[k] = L[i];
i++;
}
else{
arr[k] = R[j];
j++;
}
}
}
printArray(arr);
}
public static void printArray(int[] arrayToPrint) {
for (int i = 0; i < arrayToPrint.length; i++) {
System.out.print(arrayToPrint[i] + " ");
}
System.out.print("\n");
}
}
I am working on an implementation for merge sort. But for some reason I am not getting the correct results. The answer I get when I try to sort this array is this: "1 2 2 3 4 5 6 6". I don't understand where "7" goes. And if I remove an element from the array I get an ArrayIndexOutOfBoundsException.
With the array out of bounds exception, I dont understand where exactly I am going wrong. I increased the size of the array but it doesnt change the result. Am I looking at it with an incorrect approach?
Thanks!