Heap Sort

Binary Tree Representation

76329196349097945036
Active
Target
Pivot

Array Representation

7
63
29
19
6
34
90
97
94
50
36
FastSlow
Starting Heap Sort: Building Max Heap...
Time Complexity
Best
O(nlog⁡n)O(n \log n)
Average
O(nlog⁡n)O(n \log n)
Worst
O(nlog⁡n)O(n \log n)
Space Complexity
O(1)O(1)
StabilityFALSE
In-placeTRUE

Explanation

Heap Sort

Heap Sort is a comparison-based sorting technique based on Binary Heap data structure. It is similar to selection sort where we first find the maximum element and place the maximum element at the end. We repeat the same process for the remaining elements.

How it works

  1. Build a Max Heap from the input data.
  2. At this point, the largest item is stored at the root of the heap. Replace it with the last item of the heap followed by reducing the size of heap by 1. Finally, heapify the root of tree.
  3. Repeat step 2 while size of heap is greater than 1.

Complexity

  • Time Complexity: O(nlog⁡n)O(n \log n) for all cases (best, average, and worst).
  • Space Complexity: O(1)O(1) as it is an in-place algorithm.
  • Stability: Not stable.

Pseudo Code

1procedure heapSort(A)
2 buildMaxHeap(A)
3 for i from A.length - 1 down to 1
4 swap(A[0], A[i])
5 maxHeapify(A, 0, i)
6end procedure
7
8procedure maxHeapify(A, i, size)
9 l = 2i + 1, r = 2i + 2
10 largest = i
11 if l < size and A[l] > A[i]
12 largest = l
13 if r < size and A[r] > A[largest]
14 largest = r
15 if largest != i
16 swap(A[i], A[largest])
17 maxHeapify(A, largest, size)
18end procedure
Sponsor Ad