Heap Sort - Algorithm, Visualization, Examples
Visualization Player
Problem Statement
Examples
Solution
Algorithm Steps
Code
C
C++
Python
Java
JS
Go
Rust
Kotlin
TS
#include <stdio.h>
void heapify(int arr[], int n, int i) {
int largest = i;
int left = 2 * i + 1;
int right = 2 * i + 2;
if (left < n && arr[left] > arr[largest])
largest = left;
if (right < n && arr[right] > arr[largest])
largest = right;
if (largest != i) {
int temp = arr[i];
arr[i] = arr[largest];
arr[largest] = temp;
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--) {
int temp = arr[0];
arr[0] = arr[i];
arr[i] = temp;
heapify(arr, i, 0);
}
}
int main() {
int arr[] = {6, 3, 8, 2, 7, 4};
int n = sizeof(arr)/sizeof(arr[0]);
heapSort(arr, n);
printf("Sorted array is: ");
for (int i = 0; i < n; i++)
printf("%d ", arr[i]);
return 0;
}
Time Complexity
Case | Time Complexity | Explanation |
---|---|---|
Best Case | O(n log n) | Building the max heap takes O(n) time, and the subsequent n extractions each require O(log n) heapify operations, resulting in O(n log n) even in the best case. |
Average Case | O(n log n) | Heap sort performs n extract-max operations, and each requires a heapify step that takes O(log n) time. This results in an average-case time complexity of O(n log n). |
Worst Case | O(n log n) | In the worst case, every extraction causes the largest number of heapify steps (log n), repeated n times. Thus, the overall time complexity is O(n log n). |
Comments
Loading comments...