Heap Sort
Algorithm · Stretch
Step through it: Top K Elements pattern
Step 1 of 6
Goal: find the 3 biggest numbers. Sorting everything works but does more than needed. Instead keep a small club of the best 3 so far and always know its weakest member, the first to be kicked out. (A min-heap gives you the weakest in one step.)
Step 2 of 6
Take in 5, 1 and 9. The club is full: 1, 5, 9. The weakest member is 1.
Step 3 of 6
Next is 3. It beats the weakest (1), so 1 leaves and 3 joins: 3, 5, 9.
Step 4 of 6
7 beats the new weakest (3). Club: 5, 7, 9.
Step 5 of 6
2 is smaller than the weakest (5), so ignore it. The club is the answer: 5, 7, 9. Each number costs one quick heap update, about n log k steps in all. This is the Top K pattern.
Step 6 of 6
Your turn.
Complexity
| Name | Best | Average | Worst | Memory | Stable | Comments |
|---|---|---|---|---|---|---|
| Heap sort | n log(n) | n log(n) | n log(n) | 1 | No |
Heapsort is a comparison-based sorting algorithm. Heapsort can be thought of as an improved selection sort: like that algorithm, it divides its input into a sorted and an unsorted region, and it iteratively shrinks the unsorted region by extracting the largest element and moving that to the sorted region. The improvement consists of the use of a heap data structure rather than a linear-time search to find the maximum.
Code
import Sort from '../Sort';
import MinHeap from '../../../data-structures/heap/MinHeap';
export default class HeapSort extends Sort {
sort(originalArray) {
const sortedArray = [];
const minHeap = new MinHeap(this.callbacks.compareCallback);
// Insert all array elements to the heap.
originalArray.forEach((element) => {
// Call visiting callback.
this.callbacks.visitingCallback(element);
minHeap.add(element);
});
// Now we have min heap with minimal element always on top.
// Let's poll that minimal element one by one and thus form the sorted array.
while (!minHeap.isEmpty()) {
const nextMinElement = minHeap.poll();
// Call visiting callback.
this.callbacks.visitingCallback(nextMinElement);
sortedArray.push(nextMinElement);
}
return sortedArray;
}
}References
Practice
Top K Elements
- Kth Largest Element in a StreamEasy
- Last Stone WeightEasy
- Kth Largest Element in an ArrayMedium
- Top K Frequent ElementsMedium
- Top K Frequent WordsMedium
- K Closest Points to OriginMedium
- Sort Characters By FrequencyMedium
- Task SchedulerMedium
- Reorganize StringMedium
- Find K Pairs with Smallest SumsMedium
- Kth Smallest Element in a Sorted MatrixMedium
- Meeting Rooms IIMedium
- Furthest Building You Can ReachMedium
- Merge k Sorted ListsHard
- Find Median from Data StreamHard
- Smallest Range Covering Elements from K ListsHard
Sort First
- Contains DuplicateEasy
- Valid AnagramEasy
- Meeting RoomsEasy
- Merge Sorted ArrayEasy
- Sort ColorsMedium
- Largest NumberMedium
- H-IndexMedium
- Wiggle Sort IIMedium
- Sort an ArrayMedium
- Custom Sort StringMedium
- Insertion Sort ListMedium
- Maximum GapHard
- Count of Smaller Numbers After SelfHard
Spotted a mistake or something unclear? Report it on GitHub.