[Geeks for Geeks] Heap Sort

Heap Sort

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.

  • Time : O(nlogn)
  • Space : O(1)
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
class Solution {
public:
//Heapify function to maintain heap property.
void heapify(int arr[], int n, int i) {
if(!i) return;
int par = (i - 1) / 2;
if(arr[par] < arr[i]) {
swap(arr[par], arr[i]);
heapify(arr, n, par);
}
}

void balance(int arr[], int n, int i) {
int left = i * 2 + 1, right = i * 2 + 2;
if(left >= n) return;
if(right >= n) {
if(arr[left] > arr[i]) {
swap(arr[left], arr[i]);
balance(arr, n, left);
}
} else {
if(arr[left] > arr[right]) {
if(arr[left] > arr[i]) {
swap(arr[left], arr[i]);
balance(arr, n, left);
}
} else {
if(arr[right] > arr[i]) {
swap(arr[right], arr[i]);
balance(arr, n, right);
}
}
}
}

int pop(int arr[], int n) {
int res = arr[0];
swap(arr[0], arr[n]);
balance(arr, n, 0);
return res;
}

public:
//Function to build a Heap from array.
void buildHeap(int arr[], int n) {
for(int i = 0; i < n; i++)
heapify(arr, i, i);
}


public:
//Function to sort an array using Heap Sort.
void heapSort(int arr[], int n) {
buildHeap(arr, n);

for(int i = n - 1; i > 0; i--) {
int ma = pop(arr, i);
arr[i] = ma;
}
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/05/20/PS/GeeksforGeeks/heap-sort/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.