C++ Program to Implement Heap Sort



The Heap Sort is a comparison-based sorting algorithm that sorts the numbers using a binary heap. It is an in-place sorting method, that means it sorts the array without needing any extra space.

In this article, we have been given an unsorted array and our task is to implement the heap sort in C++.

What is Heap Sort?

The heap sort is an efficient sorting technique that first constructs the heap ADT and then removes the root element to swap it with the node having minimum value at the leaf position. Then we use the heapify method to rearrange the elements accordingly.

The heap sort follows two steps that are:

  • The first step is to build a max heap by arranging the array into a binary heap (where each parent node is greater than its children) by placing the largest element at the root element.
  • The second step is to remove elements, where we remove the root (largest) element, place it at the end of the array, and rebuild the heap. Then we repeat this process until the whole array is sorted.

What is Heapify?

Heapify is the process used to maintain the heap property in a binary heap. When a new element is added to the heap, it might not satisfy the heap property. In such cases, heapify helps to fix this by adjusting the heap structure.

For example, in a max-heap, the parent node should always be greater than or equal to its children. If a parent node is smaller than its child, heapify swaps them. This process repeats until the heap property is restored.

Example

Consider the following heap before heapifying:

heapify first part

In the above image, the heap property is violated because element1 is smaller than its parent element 31. The element 1 is not at the correct position according to the heap property. To fix this, we start heapifying from element 1. We compare it with its children and move it down the tree until the heap property is satisfied.

Heapify Process

To heapify, we follow these steps:

  • Start with element 1. Compare it with its children, 9 and 10. Since 1 is smaller than both, we swap it with the larger child, which is 10:
  • heapify first part

  • Next, compare element 1 with its new children, 8 and 7. We swap 1 with the larger child, 8:
  • heapify first part

  • Now, the heap property is satisfied, as each parent is greater than or equal to its children.

How Heap Sort Works?

The heap sort works by first building a max heap and then sorting it by repeatedly moving the largest element to the end. Here's how it works step by step:

  • We start heap sort technique with building a max heap first by arranging the array according to max heap rule i.e. each parent is greater than its children.
  • Then, we swap the largest element i.e. root element with the last element of the array. Now, largest element is placed at the end.
  • Then we reduce the heap size by one and keep sorting the unsorted portion of the array.
  • Then we heapify to move the largest element to the root, as after swapping, the new root might not follow the max heap property.
  • Then we repeat this process of swapping and heapifying until the whole array is sorted.

Let's understand the working of heap sort with a visual example:

Working of heapsort_1

Working of heapsort_2

C++ Implementation of Heap Sort

Here's a complete C++ code for heap sort where:

  • We first build a max-heap using the createHeap() function by calling heapify from the last non-leaf node. The createHeap() function accepts the array arr and number of elements n as arguments.
  • Then, in the heapSort() function, we repeatedly swap the root (largest element) with the last element, reduce the heap size, and heapify so that it follows the max-heap property.
  • We keep repeating the above steps until the array is sorted.
#include <iostream>
using namespace std;

// Function to heapify a subtree rooted at index i
void heapify(int arr[], int n, int i) {
    int largest = i;  // Initialize largest as root
    int left = 2 * i + 1;  // Left child index
    int right = 2 * i + 2;  // Right child index

    // If left child is larger than root
    if (left < n && arr[left] > arr[largest])
        largest = left;

    // If right child is larger than largest so far
    if (right < n && arr[right] > arr[largest])
        largest = right;

    // If largest is not root, swap and heapify the affected subtree
    if (largest != i) {
        swap(arr[i], arr[largest]);
        heapify(arr, n, largest);  // Recursively heapify the affected subtree
    }
}

// Function to create a max-heap from the input array
void createHeap(int arr[], int n) {
    // Start from the last non-leaf node and heapify each node
    for (int i = n / 2 - 1; i >= 0; i--) {
        heapify(arr, n, i);
    }
}

// Heap sort function
void heapSort(int arr[], int n) {
    createHeap(arr, n);  // Create a max-heap

    // One by one extract elements from the heap
    for (int i = n - 1; i > 0; i--) {
        // Move current root (largest element) to the end of the array
        swap(arr[0], arr[i]);

        // Heapify the reduced heap
        heapify(arr, i, 0);
    }
}

// Function to print an array
void printArray(int arr[], int n) {
    for (int i = 0; i < n; i++)
        cout << arr[i] << " ";
    cout << endl;
}

int main() {
    int arr[] = {4, 10, 3, 5, 1};
    int n = sizeof(arr) / sizeof(arr[0]);

    cout << "Unsorted array: ";
    printArray(arr, n);

    heapSort(arr, n);

    cout << "Sorted array: ";
    printArray(arr, n);
    return 0;
}

The output of the above code is:

Unsorted array: 4 10 3 5 1 
Sorted array: 1 3 4 5 10 

Complexity of Heap Sort

Time Complexity: The time complexity of the heap sort is O(n logn) as building the heap takes O(n) time, and each swap and re-heapify operation takes O(log n) time. So, the overall time complexity becomes O(n log n).

Space Complexity: The space complexity of the heap sort is O(log n) due to the recursion depth in the heapify function.

Conclusion

In this article, we learned how to implement Heap Sort in C++, a sorting algorithm that uses a binary heap. We built a Max Heap and sorted the array by removing the largest element and adjusting the heap. Heap Sort is efficient with a time complexity of O(n log n) and a space complexity of O(log n).

Updated on: 2025-04-17T16:55:01+05:30

853 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements