Heap Sort

πŸ“˜ Data Structure and Algorithm πŸ‘ 73 views πŸ“… Nov 05, 2025
⏱ Estimated reading time: 1 min

Heap Sort Algorithm

Heap Sort is a comparison-based sorting algorithm that uses a binary heap data structure to efficiently find and remove the largest (or smallest) element repeatedly.

Algorithm Steps

  1. Build a max heap from the input data.
  2. Swap the root (maximum) with the last element.
  3. Reduce the heap size and heapify again.
  4. Repeat until all elements are sorted.

Example (C++)

void heapify(int arr[], int n, int i) {
    int largest = i;
    int l = 2 * i + 1;
    int r = 2 * i + 2;

    if (l < n && arr[l] > arr[largest])
        largest = l;
    if (r < n && arr[r] > arr[largest])
        largest = r;

    if (largest != i) {
        swap(arr[i], arr[largest]);
        heapify(arr, n, largest);
    }
}

void heapSort(int arr[], int n) {
    for (int i = n / 2 - 1; i >= 0; i--)
        heapify(arr, n, i);

    for (int i = n - 1; i > 0; i--) {
        swap(arr[0], arr[i]);
        heapify(arr, i, 0);
    }
}

Time Complexity

  • All Cases: O(n log n)

Advantages

  • Consistent O(n log n) performance.
  • In-place sorting, no extra space needed.

Disadvantages

  • Not a stable sort.
  • More complex than insertion or selection sort.

Conclusion

Heap Sort is a reliable, efficient, and in-place sorting algorithm widely used where consistent performance is required.


πŸ”’ Some advanced sections are available for Registered Members
Register Now

Share this Post


← Back to Tutorials

Popular Competitive Exam Quizzes