forked from Vatsalparsaniya/Data-Structure
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathHeap_sort.cpp
More file actions
126 lines (92 loc) · 1.86 KB
/
Copy pathHeap_sort.cpp
File metadata and controls
126 lines (92 loc) · 1.86 KB
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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
#include <iostream>
#include <vector>
using namespace std;
template <typename T>
bool greater_c(const T a,const T b)
{
return a > b;
}
template <typename T>
bool lower_c(const T a, const T b)
{
return a < b;
}
size_t left(const size_t node)
{
return node << 1;
}
size_t right(const size_t node)
{
return 1 + (node << 1);
}
size_t parent(const size_t node)
{
return node >> 1;
}
template <typename T>
void max_heapify(vector<T> & heap, size_t position, size_t heap_size, bool comparator(T, T))
{
size_t l = left(position);
size_t r = right(position);
size_t high_priority;
if(l < heap_size and comparator(heap[position], heap[l]))
{
high_priority = l;
}
else
{
high_priority = position;
}
if(r < heap_size and comparator(heap[high_priority], heap[r]))
{
high_priority = r;
}
if(high_priority != position)
{
swap(heap[position], heap[high_priority]);
max_heapify(heap, high_priority, heap_size, comparator);
}
}
template <typename T>
void build_heap(vector<T> & heap, bool comparator(T, T))
{
for(size_t i = heap.size() - 1; ; i--)
{
max_heapify(heap, i, heap.size(), comparator);
if(i == 0)
break;
}
}
template <typename T>
void heap_sort(vector<T> & heap, bool comparator(T, T) = lower_c)
{
build_heap(heap, comparator);
size_t heap_size = heap.size();
for(size_t i = heap.size() - 1; i >= 1; i--)
{
swap(heap[0], heap[i]);
heap_size--;
max_heapify(heap, 0, heap_size, comparator);
}
}
int main(int argc, char ** argv){
bool print_input = true;
if(argc > 1 and argv[1][1] == 'v')
print_input = false;
size_t n;
if(print_input)
cout<<"Array size: ";
cin>>n;
vector<int> arr(n);
if(print_input)
cout<<"Array elements: ";
for(size_t i = 0; i < n; i++)
cin>>arr[i];
heap_sort(arr);
if(print_input)
cout<<"Sorted array: ";
for(size_t i = 0; i < n; i++)
cout<<arr[i]<<' ';
cout<<endl;
return 0;
}