-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathheap_sort.cpp
More file actions
52 lines (41 loc) · 937 Bytes
/
heap_sort.cpp
File metadata and controls
52 lines (41 loc) · 937 Bytes
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
#include <bits/stdc++.h>
using namespace std;
void heapify(vector<int> &heap, int len, int i)
{
int largest = i;
int left = 2 * i + 1;
int right = 2 * i + 2;
if (left < len && heap[left] > heap[i])
largest = left;
if (right < len && heap[right] > heap[largest])
largest = right;
if (largest != i)
{
swap(heap[largest], heap[i]);
heapify(heap, len, largest);
}
}
void heap_sort(vector<int> &heap)
{
int n = heap.size();
int start_index = (n / 2) - 1;
// build max heap
for (int i = start_index; i >= 0; i--)
{
heapify(heap, n, i);
}
// start sorting
for (int i = n - 1; i >= 1; i--)
{
swap(heap[i], heap[0]);
heapify(heap, i, 0);
}
}
int main()
{
vector<int> heap = {9, 6, 0, 5, 0, 8, 2, 4, 7}; // Input array
heap_sort(heap);
for (int i : heap)
cout << i << " ";
return 0;
}