0

I was working with algorithms and specifically heapsort. From my understanding the heapsort algorithm involves preparing the list by first turning it into a max heap.

Turning my

[2, 8, 5, 3, 9, 1]

Into
[9, 8, 5, 3, 2, 1]

With heapsort I am supposed to swap 9 with 1. But by looking at the array straight after max heaping, i see a sorted list in decreasing order. Why is swapping required when the list is already sorted in decreasing order?

This was just thoughts I had after watching: https://www.youtube.com/watch?v=2DmK_H7IdTo

Rainoa
  • 491
  • 1
  • 4
  • 14

2 Answers2

5

After making it a heap, it's not necessarily sorted in descending order.

A heap only requires that every node be bigger (or smaller, for min-heap) than its children, but says nothing about the order of the children, nor the relation of nodes at different levels (where one isn't a direct descendent of the other, see 5 and 6 below). This means that this would also be a valid heap:

     9
   /   \
  5     8
 / \   /
1   2 6

[9, 5, 8, 1, 2, 6]
Bernhard Barker
  • 54,589
  • 14
  • 104
  • 138
1

For your question

Why is swapping required when the list is already sorted in decreasing order?

By definition: The heap data structure is a complete binary tree with the property its root is greater (or smaller) than its children.

The heapify() function guarantees the construction of heap. And in your case it happened to be in descending order. The other case is pointed out in answer of Dukeling, which is not in decending order.

In heap sort, after the first heapify() call, we know only one thing. Root of the heap (1st element in array) is the Max element in array. Thus, move it to its position (last place) and reduce the array size by 1 and apply same steps again for all elements.

The heapify() operation will be O(log n) and hence the total complexity of O(n log n)

Hope it helps!

arunk2
  • 2,246
  • 3
  • 23
  • 35