Search code examples
algorithmrecursionheapsortmin-heap

What is wrong with my Heapsort algorithm for building a min heap?


I'm prepping for software developer interviews and have been working on algorithm problems. My book shows a Heapsort algorithm that can sort an unordered array in increasing order. I'm trying to modify it so it can sort with a min heap. But when I follow the logic in the code it doesn't get my array sorted correctly. What is wrong with my code (in pseudocode)?

The array to be sorted: 16, 14, 10, 8, 7, 9, 3, 2, 4, 1

The book's Heapsort algorithm using max-heapify:

HEAPSORT(A)
  BUILD-MAX-HEAP(A)
    for i = A.length down to 2
      swap A[1] with A[i]
      A.heapsize = A.heapsize - 1
      MAX-HEAPIFY(A, 1)

MAX-HEAPIFY(A)
  l = Left(i)
  r = Right(i)
  if l <= A.heapsize and A[l] > A[i]
    largest = l
  else
    largest = i
  if r <= A.heapsize and A[r] > A[largest]
    largest = r
  if largest != i
    swap A[i] with A[largest]
    MAX-HEAPIFY(A, largest)

My modified code using min-heapify:

HEAPSORT(A)             // where A is an array
  BUILD-MIN-HEAP(A)
    for i = A.length down to 2
      swap A[1] with A[i]
      A.heapsize = A.heapsize + 1
      MIN-HEAPIFY(A, 1)

MIN-HEAPIFY(A, i)
  l = Left(i)
  r = Right(i)
  if l <= heapsize.A and A[l] < A[i]
    smallest = l
  else
    smallest = i
  if r <= heapsize.A and A[r] < A[smallest]
    smallest = r
  if smallest != i
    swap A[i] with A[smallest]
    MIN-HEAPIFY(A, smallest)

Solution

  • Heap sort runs in two phases: (1) transform the unsorted array into a heap, (2) transform the heap into a sorted array.

    For building up the heap, the for-loop should run from 2 to A.length; also the heap size should become larger, not smaller.

    The code snippet for BUILD-MAX-HEAP(A) seems to be meant for phase 2, for building up the sorted array out of the heap.

    The phase 1 would build up the heap in the beginning of the array by letting new nodes "bubble up" in the heap. As long as the new node is larger (or smaller if you generate a min-heap) than its parent, exchange it with its parent.