[AlgoExpert] Heap Sort

Heap Sort

  • Time : O(nlogn)
  • Space : O(n)
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
#include <vector>
using namespace std;

void push(vector<int>& heap, int v) {
heap.push_back(v);
int i = heap.size() - 1;
while(i) {
if(heap[i] < heap[i / 2])
swap(heap[i], heap[i / 2]);
else break;
i /= 2;
}
}

int pop(vector<int>& heap) {
int res = heap[0];
heap[0] = heap.back();
heap.pop_back();
int i = 0;
while(true) {
if(i * 2 + 1 < heap.size()) {
int mi = min(heap[i * 2], heap[i * 2 + 1]);
if(mi >= heap[i]) break;
if(heap[i * 2] == mi) {
swap(heap[i], heap[i * 2]);
i = i * 2;
} else {
swap(heap[i], heap[i * 2 + 1]);
i = i * 2 + 1;
}
} else if(i * 2 < heap.size()) {
if(heap[i * 2] >= heap[i]) break;
swap(heap[i], heap[i * 2]);
i = i * 2;
} else break;
}

return res;
}

vector<int> heapSort(vector<int> array) {
vector<int> heap;
for(auto& n : array)
push(heap, n);
int idx = 0;
while(!heap.empty()) {
array[idx++] = pop(heap);
}
return array;
}

Author: Song Hayoung
Link: https://songhayoung.github.io/2022/05/10/PS/AlgoExpert/heap-sort/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.