Skip to main content

Heap Sort

Definition​

Heap Sort is a comparison-based sorting algorithm that operates by converting the array into a binary heap structure, then repeatedly removing the maximum element from the heap and rebuilding the heap

Practice​

procedure heapSort(array)
n := length(array)

// Build Max Heap
for i from n/2 - 1 down to 0 do
heapify(array, n, i)

// Heapify and Extract Maximum
for i from n - 1 down to 0 do
swap(array[0], array[i]) // Move current root to end
heapify(array, i, 0) // Heapify the reduced heap

procedure heapify(array, heapSize, index)
largest := index
leftChild := 2 * index + 1
rightChild := 2 * index + 2

// Find the largest element among root, left child, and right child
if heapSize > leftChild and array[leftChild] > array[largest] then
largest := leftChild
if heapSize > rightChild and array[rightChild] > array[largest] then
largest := rightChild

// Swap and continue heapifying if necessary
if largest != index then
swap(array[index], array[largest])
heapify(array, heapSize, largest)