My code is working during compilation but the runtime error points to an if condition in my MaxHeapify
function. I marked it out. Any help would be simply lovely, and would make me stop banging my head against the wall.
public class HeapSort {
public static void main(String[] args) {
int A[] = {-100, 1, 2, 5, 7, 2, 9};
Heapsort(A);
//System.out.println(A.length);
for (int x = 1; x < A.length; x++) {
System.out.println(A[x] + " ");
}
}
public static void Build_MAX_heap(int A[]) {
int n = A.length;
for (int i = n / 2; i >= 1; i--) {
MAX_heapify(A, i);
}
}
public static void MAX_heapify(int A[], int i) {
int heapsize = A.length;
int l = 2 * i;
int r = 2 * i + 1;
//find the largest of A[i].A[l],A[r]
int largest = i;
if (A[l] > A[largest]) {
largest = l;
if (A[l] > A[largest] && l <= heapsize) {
largest = l;
}
if (A[r] > A[largest] && r <= heapsize) { //runtime error here
largest = r;
}
if (largest != i) {
int temp = A[i];
A[i] = A[largest];
A[largest] = temp;
MAX_heapify(A, largest);
}
}
}
public static void Heapsort(int A[]) {
Build_MAX_heap(A);
int heapsize = A.length;
for (int last = heapsize; last >= 2; last--) {
int temp = A[1];
A[1] = A[last];
A[last] = temp;
heapsize--;
MAX_heapify(A,1);
}
}
}
Variable r
is set to:
int r = 2 * i + 1;
In first case of loop:
for (int i = n / 2; i >= 1; i--) {
MAX_heapify(A, i);
}
i
is n/2
so to function is passed:
MAX_heapify(A,n/2);
and r
is 2 * (n/2) + 1
which is n+1
when you want to do this line
if (A[r] > A[largest] && r <= heapsize) {
then A[r]
is A[n+1]=A[A.length+1]
- this causes IndexOutOfBoundsException