Back to Dashboard
Heap Sort
An efficient sorting algorithm that builds a binary heap from the data and repeatedly extracts the maximum element to build the sorted array.
Binary Tree Representation
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
Average
Worst
Space Complexity
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
- Build a Max Heap from the input data.
- 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.
- Repeat step 2 while size of heap is greater than 1.
Complexity
- Time Complexity: for all cases (best, average, and worst).
- Space Complexity: 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 14 swap(A[0], A[i])5 maxHeapify(A, 0, i)6end procedure78procedure maxHeapify(A, i, size)9 l = 2i + 1, r = 2i + 210 largest = i11 if l < size and A[l] > A[i]12 largest = l13 if r < size and A[r] > A[largest]14 largest = r15 if largest != i16 swap(A[i], A[largest])17 maxHeapify(A, largest, size)18end procedure
Sponsor Ad