Day 28: Heapsort Algorithm
Heapsort Algorithm#
Welcome to Day 28 of our 60 Days of Coding Algorithm Challenge! Today, we’ll explore the Heapsort algorithm, an efficient, comparison-based sorting algorithm that leverages the properties of a heap data structure.
See it in motion: watch heap sort build a max-heap and extract 100 values in order in our free interactive visualizer.
Introduction to Heapsort#
Heapsort is a sorting algorithm that uses a binary heap data structure to sort elements. It’s an in-place algorithm with an O(n log n) time complexity, making it optimal for large datasets.
How Heapsort Works#
Heapsort works in two main steps:
- Build a max heap from the input array.
- Repeatedly extract the maximum element from the heap and place it at the end of the array.
Implementing Heapsort#
Let’s implement the Heapsort algorithm:
1def heapify(arr, n, i):
2 largest = i
3 left = 2 * i + 1
4 right = 2 * i + 2
5
6 if left < n and arr[left] > arr[largest]:
7 largest = left
8
9 if right < n and arr[right] > arr[largest]:
10 largest = right
11
12 if largest != i:
13 arr[i], arr[largest] = arr[largest], arr[i]
14 heapify( …Keep your momentum going
Create a free account to unlock the full lesson, all 60 days, and track your progress as you go.
- Full access to all 60 daily lessons
- Track completion and build a daily streak
- Get interview-ready, one algorithm at a time
Join 2,900+ learners · 4.8/5 average rating