Heapsort
Пирамидальная сортировка
This sorting algorithm repeatedly moves the largest remaining item to the end of the unsorted part of an array. It uses a binary heap to keep track of which item is largest.
The idea behind heapsort
To sort an array in ascending order, heapsort fills it from right to left, placing the largest remaining item first. A max-heap makes that item easy to find: every parent is at least as large as its children, so the root holds a maximum. The heap does not put every item in order. In particular, siblings can appear in either order.
How the heap fits in the array
No tree objects are needed. Read the array as a binary tree laid out one level at a time. With zero-based indexing, the root is at index 0, and the children of index i are at 2*i + 1 and 2*i + 2, provided those indices are inside the current heap.
Start at the last parent, n // 2 - 1, and work backward to the root. At each parent, sift down: if its larger child is greater than it, swap the two and keep following the moved item until it has no larger child. Choosing the larger child matters: swapping with the smaller one can leave the other child greater than its new parent. Working backward means both child subtrees are already heaps when you process their parent.
Once the heap is built, swap its root with the last item in the heap. That places the maximum in its final position. Shrink the heap by one and sift down the new root. Repeat until only one item remains in the heap. The array now consists entirely of items in their final positions.
A worked example
Input: [3, 1, 4, 2]
After building the max-heap: [4, 2, 3, 1]
Swap and shrink: [1, 2, 3 | 4]
Restore the heap: [3, 2, 1 | 4]
The bar marks the boundary between the active heap on the left and the sorted suffix on the right. The next two passes put 3 and 2 into place, leaving [1, 2, 3, 4].
Costs and trade-offs
Bottom-up heap construction takes O(n) time. Although a sift from the root can travel O(log n) levels, most nodes are near the leaves and can move only a short distance. The extraction phase takes up to O(n log n) time, giving the same bound for the whole sort in the worst case. An iterative implementation needs only O(1) extra space; a recursive sift also uses call-stack space.
Heapsort is not stable: swapping the root with the end of the heap can reverse the relative order of records with equal keys. It is useful when you need to sort in place and guarantee a worst-case time bound. Introsort, for example, uses heapsort as a fallback when quicksort-style partitioning goes too deep.
What to expect in an interview
Be ready to explain why heap construction is linear rather than just multiplying the number of nodes by the cost of the deepest sift. If asked to code the algorithm, keep the heap size separate from the array length. After each swap, reduce the heap size before sifting so that the sorted suffix stays untouched. Test the sift with a parent that has only a left child.