I'm learning Java and I make this merge sort program but it throws an Exception of ArrayOutOfBound. What is my mistake?
I also use this code at array.length or array.length-1 but both the cases are failed. It seems my code is not accepting the array's length.
// To divide the array---
void divide(int a[], int lb, int ub) {
if (lb < ub) {
int mid = (lb + ub) / 2;
divide(a, lb, mid);
divide(a, mid + 1, ub);
merge(a, lb, mid, ub);
}
}
//For printing the actual array---
static void ActualArray(int a[]) {
System.out.println("----!!!Merge Sort!!!----");
System.out.println("Your Array is: ");
for (int i : a) {
System.out.print(i + " ");
}
System.out.println("\n");
}
//For merging the Array
void merge(int a[], int lb, int mid, int ub) {
int i = lb;
int j = mid + 1;
int k = lb;
int b[] = {};
while (i <= mid && j <= ub) {
if (a[i] < a[j]) {
b[k] = a[i];
i++;
} else {
b[k] = a[j];
j++;
}
k++;
}
if (i > mid) {
while (j <= ub) {
b[k] = a[j];
j++;
k++;
}
} else {
while (i <= mid) {
b[k] = a[i];
i++;
k++;
}
}
System.out.println("Your Sorted Array is: ");
for (int ele : b) {
System.out.print(ele + " ");
}
}
// Main Method
public static void main(String args[]) {
int arr[] = { 25, 16, 45, 17, 84, 61 };
ActualArray(arr);
MergeSort obj = new MergeSort();
obj.divide(arr, 0, arr.length - 1);
}

j <= ubshould bej < ub.j <= ubis correct for this implementation. The OP follows the error prone but very common convention where the slice runs fromarr[lb]toarr[ub]included. I wish teachers would stop this non-sense.