void Heapify( int *Array, int index, int heapSize );
void BuildHeap( int *Array, int arraySize );
void Heapsort( int *Array, int arraySize );
Remember that the algorithms as listed in the book assume the array starts with index 1 but in C++ arrays start with index 0. You will need to modify the algorithms to deal with this. For example, line 6 of the HEAPIFY algorithm (page 143) says:
if r <= heap-size[A] and A[r] > A[largest]
When converting this statement to C++, you would write something like:
if ( r < heapSize && A[r] > A[largest] )
Notice that the <= was changed to <. Why?
You will also need to create functions for the LEFT and RIGHT algorithms given on page 141 of the book. Notice that the formulas given for these operations do not work properly with 0-indexed arrays. This can easily be rectified, however, by doing the following in each function:
Once the user has entered the size, your function should dynamically allocate an array of the desired size using the new function (make sure and check that the memory allocation succeeded), populate the array with numbers sorted in descending order, print the contents of the array, call the Heapsort function, then print out the contents of the array again to show that they have been sorted.
Following is a sample run of the completed program:
This program will take an array of numbers in descending order and sort them
into ascending order using the heapsort algorithm.
Please enter an integer from 1 - 1000000: -5
Please enter an integer from 1 - 1000000: 5
The array before sorting: 5 4 3 2 1
The array after sorting: 1 2 3 4 5