I’m kind of new to algorithms and wanted to implement heap sort algorithm.
The algorithm is given as follows:
Parent(i)
return Math.floor(i/2)
Left(i)
return 2i
Right(i)
return 2i+1
Then there is HEAPIFY method that restores the heep property. Algorithm is as follows:
HEAPIFY(A, i)
l = Left(i)
r = Right(i)
if (l <= heap-size[A] and A[l] > A[i]
then largest = l
else largest = i
if r <= heap-size[A] and A[r] > A[largest]
then largest = r
if largest != i
then exchange A[i] <-> A[largest]
HEAPIFY(A, largest)
My Code that implements this method is:
public static void HEAPIFY(int[] A, int i) {
int l = LEFT(i);
int r = RIGHT(i);
int largest = 0;
if (l < A.length && A[l] > A[i]) {
largest = l;
} else {
largest = i;
}
if (r < A.length && A[r] > A[largest]) {
largest = r;
}
if (largest != i) {
int temp = A[i];
A[i] = A[largest];
A[largest] = temp;
HEAPIFY(A, largest);
}
}
Now My question is in the book algorithm is shown by drawing the tree of heap and array
so for example array is: [16,14,10,8,7,9,3,2,4,1] and for the tree and also for array it is indexed starting from 1 to n, so Array[1] = 16 and in coding Array[0] = 16. Now i can not adjust the heapify method to start either from index 1 and go up to 1 or somehow make it start from 0 and let the heap be indexed from 0 to n-1.
Sorry if its kind of confusing i’m still confused but i would really appreciate some help.
Thank you guys
Now HEAPIFY works and the following code is code to build the heap:
public static void BUILD_HEAP(int[] A) {
heapSize = A.length;
for (int i = (int) Math.floor(A.length / 2.0); i >= 0; i--) {
HEAPIFY(A, i);
}
}
build heap also works and the only method that doesnot work is heapsort.
public static void HEAPSORT(int[] A) {
BUILD_HEAP(A);
for (int i = A.length-1; i >= 1; i--) {
int temp = A[0];
A[0] = A[i];
A[i] = temp;
heapSize = heapSize-1;
HEAPIFY(A,0);
}
}
this has to sort but when i try to traverse the array after the call of heapsort it does not give the sorted array.
any ideas how to fix heapsort?
if you want to start form index 1,then you can initialize the array like this:
[-x,16,14,10,8,7,9,3,2,4,1] -x is the array[0],in other words,you can ignore the element which is in array[0].
if you want to start form index 0,then you have to modify the function LEFT(i) and RIGHT(i).