Python Program for Heap Sort
Intermediate · Searching and sorting
A max heap is a list arranged like a tree in which every parent is at least as big as its children, so the largest value is always at index 0. The children of index i sit at indexes 2i + 1 and 2i + 2. Heap sort builds a max heap, then keeps moving the largest value to the end of the list and repairing the heap, until everything is sorted.
Program
Original list: [12, 11, 13, 5, 6, 7] Max heap: [13, 11, 12, 5, 6, 7] Moved 13 to the end: heap [12, 11, 7, 5, 6], sorted [13] Moved 12 to the end: heap [11, 6, 7, 5], sorted [12, 13] Moved 11 to the end: heap [7, 6, 5], sorted [11, 12, 13] Moved 7 to the end: heap [6, 5], sorted [7, 11, 12, 13] Moved 6 to the end: heap [5], sorted [6, 7, 11, 12, 13] Sorted list: [5, 6, 7, 11, 12, 13]
How it works
heapify()compares a parent with its two children and swaps it with the bigger child if needed, then keeps going down from there.- Step 1 calls
heapify()on every parent, from the last parent back to the root, which turns the whole list into a max heap. - In step 2, the root holds the largest value, so it is swapped with the last element of the heap, which is its final place.
- The heap is now one element shorter, and
heapify()on the root restores it. The printout shows the heap part shrinking and the sorted part growing. - Heap sort takes about n x log n steps and needs no extra list.
Another way to write it
Using the heapq module
Min heap: [5, 6, 7, 11, 12, 13] Sorted list: [5, 6, 7, 11, 12, 13]
Python's heapq module keeps a min heap, so popping repeatedly gives the values from smallest to largest.
Try it yourself
Change both > signs in heapify() to < and see the list come out in descending order.
Edit the program above and press Run, or open it in the full editor to save it and share it. To watch it run line by line, open it in the visualizer.
Related programs
All Python programs · CBSE class 12 practical file · Python exercises