How are heaps used for sorting?

Question

In the context of this lesson, how are heaps used for sorting?

Answer

Heaps are used for sorting by utilizing their ability to maintain the heap property each time we remove the top element of the heap.

In a min-heap, the top element will always be the current smallest element in the heap. If we remove this top element, then the heap will update to maintain the heap property, such that the next smallest element is now at the top. By continuously removing the top element, we can eventually obtain an ordered list of all elements from smallest to largest, which effectively sorts the elements.

This works the same with a max-heap, except that the top element is the current largest element. Following the same idea for removal as above, we would obtain a list of elements from largest to smallest instead, by using a max-heap.