Heap sort is performed on the heap data structure. We know that heap is a complete binary tree. Heap tree can be of two types. Min-heap or max heap. For min heap the root element is minimum and for max heap the root is maximum. After forming a heap, we can delete an element from the root and send the last element to the root. After these swapping procedure, we need to re-heap the whole array. By deleting elements from root we can sort the whole array.
The complexity of Heap Sort Technique
- Time Complexity: O(n log n)
- Space Complexity: O(1)
Input and Output
Input: A list of unsorted data: 30 8 99 11 24 39 Output: Array before Sorting: 30 8 99 11 24 39 Array after Sorting: 8 11 24 30 39 99
Algorithm
heapify(array, size)
Input − An array of data, and the total number in the array
Output − The max heap using an array element
Begin for i := 1 to size do node := i par := floor (node / 2) while par >= 1 do if array[par] < array[node] then swap array[par] with array[node] node := par par := floor (node / 2) done done End
heapSort(array, size)
Input: An array of data, and the total number in the array
Output −nbsp;sorted array
Begin for i := n to 1 decrease by 1 do heapify(array, i) swap array[1] with array[i] done End
Example
#include<iostream>
using namespace std;
void display(int *array, int size) {
for(int i = 1; i<=size; i++)
cout << array[i] << " ";
cout << endl;
}
void heapify(int *array, int n) {
int i, par, l, r, node;
// create max heap
for(i = 1; i<= n; i++) {
node = i; par = (int)node/2;
while(par >= 1) {
//if new node bigger than parent, then swap
if(array[par] < array[node])
swap(array[par], array[node]);
node = par;
par = (int)node/2;//update parent to check
}
}
}
void heapSort(int *array, int n) {
int i;
for(i = n; i>= 1; i--) {
heapify(array, i);//heapify each time
swap(array[1], array[i]);//swap last element with first
}
}
int main() {
int n;
cout << "Enter the number of elements: ";
cin >> n;
int arr[n+1]; //effective index starts from i = 1.
cout << "Enter elements:" << endl;
for(int i = 1; i<=n; i++) {
cin >> arr[i];
}
cout << "Array before Sorting: ";
display(arr, n);
heapSort(arr, n);
cout << "Array after Sorting: ";
display(arr, n);
}Output
Enter the number of elements: 6 Enter elements: 30 8 99 11 24 39 Array before Sorting: 30 8 99 11 24 39 Array after Sorting: 8 11 24 30 39 99