I was working my Algorithm's midterm review and I tried to implement all the pseudo codes by Java in order to have a better understanding of algorithm. But on the heap sort part, there was something wrong with my code. My input array is
{10,16,4,10,14,7,9,3,2,8,1}
and the first element just represents the number of elements that I would like to sort. In other words, the elements needed to be sorted start from index 1.
My output of build max-heap is : 16 14 10 8 7 9 3 2 4 1
And my output of heap sort is : 1 3 2 4 7 8 9 10 14 16
It seemed my build-max-heap part worked well but I couldn't find bugs in heap-sort part, either.
public class Midterm{
public static void main(String[] args){
int[] C = {10,16,4,10,14,7,9,3,2,8,1};
/*for convenience, the first element in array C represent the
number of elements needed to be heapified;
*/
Midterm heap = new Midterm();
int n = C.length - 1;
for (int i = (n / 2); i > 0; i--){
heap.maxHeapify(C, i, n);
}
int index = 1;
while(index <= n){
System.out.print(C[index] + " ");
index++;
}
System.out.println();
Midterm heap2 = new Midterm();
heap2.heapSort(C);
int index2 = 1;
while(index2 <= n){
System.out.print(C[index2] + " ");
index2++;
}
System.out.println();
}
public void heapSort(int[] A){
int n = A.length - 1;
for (int i = n; i >= 2; i--){
exchange(A, 1, i);
maxHeapify(A, 1, i - 1);
}
}
public void maxHeapify(int[] A, int i, int n){
int left = 2 *i, right = 2 * i + 1;
int largest;
if (left < n && A[left] > A[i]){
largest = left;
}else{
largest = i;
}
if (right < n && A[right] > A[largest]){
largest = right;
}
if (largest != i){
exchange(A, i, largest);
maxHeapify(A, largest,n);
}
}
private void exchange(int[] A, int i , int j){
int temp = A[i];
A[i] = A[j];
A[j] = temp;
}
}
There are 2 mistakes in your code:
1. The for loop for the heapsort goes from last element
to first element
, so
for (int i = n; i >= 2; i--){
should be:
for (int i = n; i >= 1; i--){
because the indices start from 0.
2. After performing a exchange(A, 1, i)
, the right call should be:
maxHeapify(A, 1, i)