HEAP09 - Editorial

Problem Link - Implement Heap Sort

Problem Statement:

Given an array of N elements. Sort the array using Heap sort.
Functions for inserting and deleting into the heap are already implemented in the code editor.

Approach:

The key idea of this solution is to use a min-heap, where the smallest element is always at the root of the heap. This allows us to repeatedly extract the smallest value efficiently. The heap operations used are:

  1. Insertion: Insert a value and maintain the heap property by bubbling up the newly inserted value.

  2. Deletion: Remove the smallest element (root), replace it with the last element, and maintain the heap property by bubbling down this element.

  3. Heapify: Used to restore the heap order after deleting the root.

Step-by-Step Explanation:

  1. Heap Class:

    • The heap is represented using a vector (v) to store elements.
  2. insert(int value):

    • Insert a value at the end of the vector and maintain the min-heap property by comparing the newly added value with its parent and swapping if necessary. This process is called bubbling up.
  3. Heapify(int index):

    • After deleting the root, this function ensures the heap property is maintained by comparing the node at index with its children and swapping with the smallest child if needed. This process is called bubbling down.
  4. delete_from_heap():

    • Remove the smallest element (root) by swapping it with the last element and removing the last element. Then, call Heapify to maintain the heap structure.
  5. Main Function:

    • We first read n values and insert them into the heap.

    • After that, we repeatedly extract the smallest element from the heap using delete_from_heap() and store it in a sorted array.

    • Finally, we print the sorted array.

This approach effectively sorts the elements by taking advantage of the heap’s ability to repeatedly extract the smallest value.

Time Complexity:

  • insert: O(log n) for each insertion due to bubbling up.

  • delete_from_heap: O(log n) for each deletion due to bubbling down.

  • Overall, for n elements, the complexity is O(n log n).

Space Complexity:

  • O(n) because we use a vector to store the heap of size n.