-
Notifications
You must be signed in to change notification settings - Fork 254
/
Copy path02 CreateHeapUsingSTLVector.cpp
71 lines (57 loc) · 1.54 KB
/
02 CreateHeapUsingSTLVector.cpp
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
#include <iostream>
#include <vector>
using namespace std;
void Insert(vector<int>& vec, int key){
// Insert key at the end
auto i = vec.size();
vec.emplace_back(key);
// Rearrange elements: O(log n)
while (i > 0 && key > vec[i % 2 == 0 ? (i/2)-1 : i/2]){
vec[i] = vec[i % 2 == 0 ? (i/2)-1 : i/2];
i = i % 2 == 0 ? (i/2)-1 : i/2;
}
vec[i] = key;
}
void InsertInplace(int A[], int n){
int i = n;
int temp = A[n];
while (i > 0 && temp > A[i % 2 == 0 ? (i/2)-1 : i/2]){
A[i] = A[i % 2 == 0 ? (i/2)-1 : i/2];
i = i % 2 == 0 ? (i/2)-1 : i/2;
}
A[i] = temp;
}
void CreateHeap(vector<int>& vec, int A[], int n){
// O(n log n)
for (int i=0; i<n; i++){
Insert(vec, A[i]);
}
}
void createHeap(int A[], int n){
for (int i=0; i<n; i++){
InsertInplace(A, i);
}
}
template <class T>
void Print(T& vec, int n, char c){
cout << c << ": [" << flush;
for (int i=0; i<n; i++){
cout << vec[i] << flush;
if (i < n-1){
cout << ", " << flush;
}
}
cout << "]" << endl;
}
int main() {
cout << "Create Heap" << endl;
int b[] = {10, 20, 30, 25, 5, 40, 35};
Print(b, sizeof(b)/sizeof(b[0]), 'b');
vector<int> v;
CreateHeap(v, b, sizeof(b)/sizeof(b[0]));
Print(v, v.size(), 'v');
cout << "Inplace Insert" << endl;
createHeap(b, sizeof(b)/sizeof(b[0]));
Print(b, sizeof(b)/sizeof(b[0]), 'b');
return 0;
}