See heap sort build a max heap from 4 10 3 5 1, then swap the root to the end and heapify again. Animated with the code, O(n log n) time and O(1) extra space.
About this algorithm
Heap sort sorts an array in O(n log n) time with no extra memory by first rearranging it into a max-heap, a binary tree stored in the array where every parent is at least as big as its children, so the largest value sits at index 0. Then it swaps that largest value to the end, shrinks the heap by one, and repairs the heap. Repeating this fills the array from the back with values in order.
Choose heap sort when you need n log n time in the worst case and cannot spare extra memory. Merge sort gives the same guarantee but needs a second array; quick sort is faster on average but can fall to n². That is why introsort, the sort in many C++ libraries, starts with quick sort and switches to heap sort if the recursion goes too deep. Heap sort is not stable and jumps around memory, so for everyday use quick sort or merge sort is usually quicker. It is selection sort with a heap doing the job of finding the maximum.
The children of index i are at 2i + 1 and 2i + 2, and its parent is at floor((i - 1) / 2). No pointers are needed.
Starting at the last parent, index floor(n / 2) - 1, and moving back to 0, sift each value down: compare it with its children, swap it with the bigger child if that child is bigger, and keep going down until it beats both children or reaches the bottom.
Swap the value at index 0, the largest in the heap, with the last value in the heap. That last slot is now final and leaves the heap.
The value now at the root is probably too small, so sift it down within the smaller heap. Repeat the swap and sift until the heap has one value left.
This page opens on 40 random bars, so type 4,10,3,5,1 into the Custom box to follow along. Building the heap starts at index 1: 10 already beats its children 5 and 1. At index 0, 4 loses to 10 and swaps, then loses to 5 and swaps again, giving the heap 10 5 3 4 1. Now 10 swaps to the end: 1 5 3 4 10. The 1 sinks below 5 and then below 4: 5 4 3 1 10. Next 5 goes to index 3: 1 4 3 5 10, and 1 sinks below 4: 4 1 3 5 10. Then 4 goes to index 2: 3 1 4 5 10, where 3 already beats 1. Finally 3 swaps with 1, and the array is 1 3 4 5 10 after 12 comparisons.
Sifting from the bottom up looks like n log n work, but half the nodes are leaves that never move, a quarter can sink only one level, and so on. Those costs add up to at most about n swaps, so the build phase is O(n). The extraction phase is what costs n log n.
Time: the heap is built in O(n), then each of the n - 1 extractions sifts a value down a tree about log n levels tall. Space: the heap lives inside the array being sorted; this page's sift-down calls itself, using up to log n stack frames, and written as a loop it needs only a few index variables.