Hello, I have tried making a merge sort method, but I am getting an Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 1 .
How do I fix this error, I have tried but I can not find the error:
public class MergeSort{
public static int[] merge_sort(int[] b){
if(b.length <= 1){
return b;
}
int midpoint = b.length/2;
int[] left = new int[midpoint];
int[] right;
if(b.length %2 == 0){
right = new int[midpoint];
}
else{
right = new int[midpoint + 1];
}
int[] result = new int[b.length];
for(int i = 0; i < midpoint; i++){
left[i] = b[i];
}
int x = 0;
for(int j = midpoint; j < b.length; j++){
if(x < right.length){
right[x] = b[j];
x++;
}
}
left = merge_sort(left);
right = merge_sort(right);
printArray(left);
printArray(right);
result = merge(left, right);
return result;
}
public static int[] merge(int[] a, int[] b){
int[] c = new int[a.length + b.length];
int e = a[0];
int g = b[0];
int eI = 0;
int gI = 0;
for(int i = 0; i < c.length-2; i++){
if(e <= g){
c[i] = e;
eI++;
e = a[eI];
}
else{
gI++;
c[i] = g;
g = b[gI];
}
}
if(a[eI] < b[gI]){
c[c.length-2] = a[eI];
c[c.length-1] = b[gI];
}
else{
c[c.length-2] = b[gI];
c[c.length-1] = a[eI];
}
return c;
}
public static void main(String[] args){
int[] a = {1,2,3};
int[] b = {4,5,6,7,9};
int[] c = merge_sort(a);
printArray(c);
}
}
P.S: printArray() method has been cut out to reduce code.