Heapsort

Learn Algorithms · 4:50

Listen on 93

Lyrics

[Verse 1]
Started with a messy array, elements scattered around
Gotta sort this data clean, best algorithm I found
First we build a binary heap, parent nodes on top
Every parent's greater than its children, never gonna stop
Take the root node that's the max, swap it to the end
Now the largest element's placed, heap size we descend
Heapify the root again, bubble down the tree
Repeat until we're sorted clean, that's the guarantee

[Chorus]
Heap it up, heap it down, max at the root we found
Swap and shrink, heapify, sorted elements all around
Build the heap, extract the max, place it at the back
Heapsort's got that O of n log n, keeping time on track

[Verse 2]
Binary heap's a complete tree, filled from left to right
Parent at index i, children at two i plus one insight
Two i plus two for the right child, that's the pattern clear
Max heap property maintained, largest values near the top tier
Heapify function bubbles down, comparing as it goes
Parent with its children nodes, largest upward flows
When the heap property breaks, we swap and continue down
Until the structure's valid again, stability we've found

[Chorus]
Heap it up, heap it down, max at the root we found
Swap and shrink, heapify, sorted elements all around
Build the heap, extract the max, place it at the back
Heapsort's got that O of n log n, keeping time on track

[Bridge]
In-place sorting algorithm, no extra space we need
Unstable but efficient, guaranteed to succeed
Not the fastest in practice, but worst case is strong
O of n log n always, never takes too long

[Verse 3]
Build heap phase starts from bottom, work our way up high
Last non-leaf node backwards, heapify we try
Then extraction phase begins, root goes to the end
Decrease the heap size by one, heapify again my friend
Continue till heap size is one, sorting is complete
Smallest to the largest now, array looking neat
From chaos to order clean, heapsort showed the way
West coast algorithm flow, sorting every day

[Chorus]
Heap it up, heap it down, max at the root we found
Swap and shrink, heapify, sorted elements all around
Build the heap, extract the max, place it at the back
Heapsort's got that O of n log n, keeping time on track

[Outro]
Heapsort mastery achieved, binary heap the key
Sorting with efficiency, algorithm royalty

← Mergesort | Insertion sort →