import java.util.Arrays;
class MergeSort {
public static int[] merge(int[] left, int[] right) {
// Initial indexes of first and second subarrays
int[] arr = new int[left.length right.length];
int countLeft = 0;
int countRight = 0;
// TODO Complete the method
while (countLeft < left.length && countRight < right.length) {
if (left[countLeft] < right[countRight]) {
arr[countLeft] = left[countLeft];
countLeft ;
} else {
arr[countRight] = left[countRight];
countRight ;
}
}
while (countLeft < left.length) {
arr[countLeft] = left[countLeft];
countLeft ;
}
while (countRight < right.length) {
arr[countRight] = left[countRight];
countRight ;
}
return arr;
}
public static int[] sort(int arr[]) {
// Find the middle point
if (arr.length > 1) {
int m = arr.length / 2;
int[] l1 = Arrays.copyOfRange(arr, 0, m);
int[] l2 = Arrays.copyOfRange(arr, m, arr.length);
l1 = sort(l1);
l2 = sort(l2);
return merge(l1, l2);
} else {
return arr;
}
}
public static void main(String[] args) {
int [] arr = {1, 6, 64, 3, 7, 3, 7};
// sort(arr);
MergeSort ob = new MergeSort();
ob.sort(arr);
System.out.println(Arrays.toString(arr));
}
}
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 1 out of bounds for length 1
at um.MergeSort.merge(MergeSort.java:28)
at um.MergeSort.sort(MergeSort.java:44)
at um.MergeSort.sort(MergeSort.java:41)
at um.MergeSort.main(MergeSort.java:55)
Anyone knows why I have the out of bounds? (I know what out of bounds means, I just don't know why I have it).
According to this is should be a out of bounds in line 28 which correspond with arr[countRight] = left[countRight];
but why?
CodePudding user response:
This looks like a copy and paste error to me. I believe you meant:
arr[countRight] = right[countRight];
CodePudding user response:
you need to change your merge method implementation. in the third while of the merge method, you should fill arr[] with the right array.
public static int[] merge(int[] left, int[] right) {
// Initial indexes of first and second subarrays
int[] arr = new int[left.length right.length];
int countLeft = 0;
int countRight = 0;
// TODO Complete the method
while (countLeft < left.length && countRight < right.length) {
if (left[countLeft] < right[countRight]) {
arr[countLeft] = left[countLeft];
countLeft ;
} else {
arr[countRight] = right[countRight];
countRight ;
}
}
while (countLeft < left.length) {
arr[countLeft] = left[countLeft];
countLeft ;
}
while (countRight < right.length) {
arr[countRight ] = right[countRight];
countRight ;
}
return arr;
}