Posts Heap Sort (geeksforgeeks - SDE Sheet)
Post
Cancel

Heap Sort (geeksforgeeks - SDE Sheet)

PROBLEM DESCRIPTION

Given an array of size N. The task is to sort the array elements by completing functions heapify() and buildHeap() which are used to implement Heap Sort.

geeksforgeeks

SOLUTION

This blog has a very detailed explantion for Heap Sort, must read: LINK

heapify:

  • Consider the current index i to be the largest.
  • Left child index = 2*i + 1
  • Right child index = 2*i + 2

  • If the element at the left child index is larger, update the largest index.
  • If the element at the right child index is larger, update the largest index.

  • If the largest index is no longer i, it means that either the left or right child has a larger value. So, we swap the elements at index i and the largest index to bring the largest element above.
  • After swapping, call heapify on the largest index since the subtree rooted at that position might now violate the heap property.

buildHeap:

  • The index of the first non-leaf node will be n/2 - 1.
  • Iterate from the last non-leaf node to the 0th index, calling heapify on each node to build the max heap.

heapSort:

  • First, we build the max heap using the buildHeap method.

  • Then, iterate from the last index (n-1) to 0. The largest element will be at the front (index 0). Swap the largest element with the current position i, effectively moving the largest element to the end of the array.
  • After the swap, call heapify for index 0 since the root may have been affected. While doing this, make sure to reduce the heap size by 1. The current heap size will be i, as we are iterating from right to left.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
class Solution
{
    // Function to build a Heap from the array.
    // A max-heap will be built, where the largest element is at the root.
    void buildHeap(int arr[], int n)
    {
        // Finding the last non-leaf node. We start heapifying from here.
        // The last non-leaf node is at index (n/2)-1.
        int lastNonLeafIdx = (n / 2) - 1;

        // Perform reverse level-order traversal (from last non-leaf node to the root),
        // and heapify each node to ensure the heap property is maintained.
        for(int i = lastNonLeafIdx; i >= 0; i--)
            heapify(arr, n, i);

    }

    // Heapify function to maintain the heap property for a subtree rooted at index 'i'.
    // 'n' is the size of the heap, and 'i' is the root of the current subtree.
    void heapify(int arr[], int n, int i)
    {
        // Assume the root is the largest initially.
        int largest = i;

        // Left child of node 'i' is at index 2*i + 1.
        int l = 2 * i + 1;

        // Right child of node 'i' is at index 2*i + 2.
        int r = 2 * i + 2;

        // If the left child exists and is greater than the root, update 'largest'.
        if(l < n && arr[l] > arr[largest])
            largest = l;

        // If the right child exists and is greater than the largest so far, update 'largest'.
        if(r < n && arr[r] > arr[largest])
            largest = r;

        // If 'largest' is not the root, we need to swap the root with the largest child.
        if(largest != i)
        {
            // Swap the current root with the largest child.
            swap(arr, largest, i);

            // Recursively heapify the affected subtree.
            heapify(arr, n, largest);
        }
    }

    // Function to sort an array using Heap Sort.
    // First, the array is transformed into a max-heap.
    // Then, the root (largest element) is swapped with the last element, and the heap size is reduced.
    // The heap is heapified again, and this process continues until the array is sorted.
    public void heapSort(int arr[], int n)
    {
        // Step 1: Build a max-heap from the given array.
        buildHeap(arr, n);

        // Step 2: One by one, move the largest element (root) to the end of the array,
        // and reduce the heap size.
        for(int i = n - 1; i > 0; i--)
        {
            // Swap the root (largest element) with the last element of the heap.
            swap(arr, i, 0);

            // Call heapify on the reduced heap (excluding the sorted elements).
            // The updated heap size will be i
            heapify(arr, i, 0);
        }
    }

    // Helper function to swap two elements in the array.
    public void swap(int[] arr, int i, int j)
    {
        // Store the value of arr[i] in a temporary variable.
        int temp = arr[i];

        // Swap arr[i] and arr[j].
        arr[i] = arr[j];
        arr[j] = temp;
    }
}
This post is licensed under CC BY 4.0 by the author.