When I implement heapsort
using a min-heap
it sorts the array from largest to smallest. Is this the desired output for a heapsort
using
Order: Use max-heapify to sort in asceding order, min-heapify to sort in descending order.
Sorting: Building the heap with min-heapify does not sort your array; it only enforces the (weaker) min-heap property, that is
A[parent(i)] <= A[i]
for every node i
other than the root. After the heap is built, the root (leftmost position in the array) has the minimum element. Sorting then repeatedly moves elements from the root to the right and calls min-heapify on the root (bringing there the minimum of what remains), hence the descending order.
The code you are posting appears correct at a glance but does not compile as is, so I cannot test. If your array appears sorted right after building the heap, it should be a coincidence. Try a larger test.