I know this is an older question, but the OP just missed the answer, with diagrams and an explanation of why the sort order looks off when listed in a liner fashion.
(so I am not going into the optimization, efficiency, etc. I am answering the visual ordering, structure of the OP quesion)
He was at pymotw.com but if he had only gotten to:
https://pymotw.com/2/heapq/
" A min-heap requires that the parent be less than or equal to its children"
So think tree, think pyramid.
This isn't a bad link at all either
https://medium.com/basecs/learning-to-love-heaps-cef2b273a238
So each parent has a two-child policy. And the kids can only have two child elements as well.
The beauty of it is that the kids will always be either less than or equal to (heap-max) to their parents or more than or equal to their parents (heap min).
heap-max or heap-min (that causes confusion) refer to the top-most element or if linear,
heap[0]. Whether that represents the max value as a start or min value as a start.
I'm going to leave the math out as much as possible.
So (numbers are indices)
heap[0] has two kids. heap[1] and heap[2].
heap[1] kids would be heap[3] and heap[4]
heap[2] kids would be heap[5] and heap[6]
heap[3] kids would be heap[7] and heap[8]
heap[4] kids would be heap[9] and heap[10]
and so on.
so, the question,
[2, 3, 5, 7, 4, 11, 6, 10, 8, 9] <<< Why is 11 put between 4 and 6?
because value 11 stored at index 5. And index 5 is a child of index 2 which has the value of 3. The value 4 (index 4) and is the child of index 1
It is ordered from smallest, it just doesn't LOOK it when examined in a linear fashion.
parent -> child
[0] -> [0] is 2
-
[0] -> [1] is 3
[0] -> [2] is 5
-
[1] -> [3] is 7
[1] -> [4] is 4
[2] -> [5] is 11 <-- between 4 and 6
[2] -> [6] is 6
so.... this again. And it is true.
"A min-heap requires that the parent be less than or equal to its children"
Make yourself crazy and pencil it out for max.... it will be true still.
(ever write one of these things and just wait to get squashed by some post doctoral?)
so let's pop off the first element and do like a normal list or queue
[0] -> [0] is 3
-
[0] -> [1] is 5
[0] -> [2] is 7
-
[1] -> [3] is 4
[1] -> [4] is 11
Let's stop.
index 1 has a value of 5. index 3, it child's value is 4 and is smaller.... the rule is broken. The heap is reordered to maintain the relationships. so it will basically, never look sorted and it won't look anything like the prior iteration of itself before popping off the value.
There are ways to reorder the node, and that second article talks bout them. I just wanted to answer the question specifically.