Not sure your image is correct. Let's build the heap as items are entered.
When you insert 2, it becomes the root. Adding 4 will make 4 the root and 2 has to go to the left subtree in order to satisfy the shape property. So you have in your array, [4, 2]
.
Now you add 5 to the end of the array and bubble it up. That results in [5, 4, 2]
. Adding 1 gives you [5, 4, 2, 1]
. That tree representation is:
5
/ \
4 2
/
1
Now, when you add 3 you get [5, 4, 2, 1, 3]
. The parent of 3 is 4, so there's no need to bubble it up, and you get:
5
/ \
4 2
/ \
1 3
Finally, you add 6 to the array and get [5, 4, 2, 1, 3, 6]
. You need to bubble 6 up. The parent of 6 is 2, so on the first pass of bubbling it up you get [5, 4, 6, 1, 3, 2]
, and bubbling up again gives you [6, 4, 5, 1, 3, 2]
. The tree representation is:
6
/ \
4 5
/ \ /
1 3 2