Reputation: 31
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);
}
Upvotes: 2
Views: 161
Reputation: 144685
There are multiple problems in your merge
method:
b
. You should write int b[] = new int[ub - lb + 1];
k
into the temporary array should be initialized to 0
, not lb
.a
.Here is a modified version:
void merge(int a[], int lb, int mid, int ub) {
int b[] = new int[ub - lb + 1];
int i = lb;
int j = mid + 1;
int k = 0;
while (i <= mid && j <= ub) {
if (a[i] < a[j]) {
b[k++] = a[i++];
} else {
b[k++] = a[j++];
}
}
// copy the remaining elements from the left part
while (i <= mid) {
b[k++] = a[i++];
}
// the remaining elements from the right part are already in the proper place
// copy back the sorted slice into the original array
for (i = 0; i < k; i++) {
a[lb + i] = b[i];
}
}
Upvotes: 1