Reputation: 47
I'm getting an out of bounds error for my implementation of mergeSort
, and I can't figure out why. This is the exact error message: Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 1 out of bounds for length 1"
Here's my implementation of mergeSort
:
public static void mergeSort(int[] arr, int n) {
if (n < 2) {
return;
}
int mid_index = n / 2;
int[] left = new int[mid_index];
int[] right = new int[n - mid_index];
for (int i = 0; i < mid_index; i++) {
left[i] = arr[i];
}
for (int i = mid_index; i < n; i++) {
right[i - mid_index] = arr[i];
}
mergeSort(left, mid_index);
mergeSort(right, n - mid_index);
merge(arr, left, right, mid_index, n - mid_index);
}
public static void merge(int[] arr, int[] left, int[] right, int left_length, int right_length) {
int i = 0;
int j = 0;
int k = 0;
while (j < left_length && k < right_length) {
if (left[i] < right[j]) {
arr[k] = left[i];
k++;
i++;
} else {
arr[k] = right[j];
k++;
j++;
}
}
while (j < left_length) {
arr[k] = left[i];
k++;
i++;
}
while (i < right_length) {
arr[k] = right[j];
k++;
j++;
}
}
Upvotes: 1
Views: 75
Reputation: 144685
All 3 while
loop in the merge
method use the wrong index variables. The first loop while (j < left_length && k < right_length) {
should be
while (i < left_length && j < right_length) {
The second loop while (j < left_length) {
should be
while (i < left_length) {
Finally, the last loop while (i < right_length) {
should be
while (j < right_length) {
Upvotes: 1
Reputation: 236
The problem was in merge
method. You make some mistakes with indexes. I corrected them in code below
public static void merge(int[] arr, int[] left, int[] right, int left_length, int right_length){
int i = 0;//left
int j = 0; //right
int k = 0;
while(i<left_length && j < right_length){
if(left[i] < right[j]){
arr[k] = left[i];
k++;
i++;
}
else{
arr[k] = right[j];
k++;
j++;
}
}
while(i<left_length){
arr[k] = left[i];
k++;
i++;
}
while(j<right_length){
arr[k] = right[j];
k++;
j++;
}
}
Upvotes: 2