forked from ashvish1831/hactoberfests
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path06 HeapifyFunctionFasterMethodtoCreateHeap.cpp
88 lines (71 loc) · 1.9 KB
/
06 HeapifyFunctionFasterMethodtoCreateHeap.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
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
#include <iostream>
using namespace std;
void swap(int A[], int i, int j){
int temp = A[i];
A[i] = A[j];
A[j] = temp;
}
int Delete(int A[], int n){
int x = A[0]; // Max element
A[0] = A[n-1];
int i = 0;
int j = 2 * i + 1;
while (j < n-1){
// Compare left and right children
if (A[j] < A[j+1]){
j = j+1;
}
// Compare parent and largest child
if (A[i] < A[j]){
swap(A, i, j);
i = j;
j = 2 * i + 1;
} else {
break;
}
}
return x;
}
void Heapify(int A[], int n){
// # of leaf elements: (n+1)/2, index of last leaf element's parent = (n/2)-1
for (int i=(n/2)-1; i>=0; i--){
int j = 2 * i + 1; // Left child for current i
while(j < n-1){
// Compare left and right children of current i
if (A[j] < A[j+1]){
j = j+1;
}
// Compare parent and largest child
if (A[i] < A[j]){
swap(A, i, j);
i = j;
j = 2 * i + 1;
} else {
break;
}
}
}
}
template <class T>
void Print(T& vec, int n, string s){
cout << s << ": [" << flush;
for (int i=0; i<n; i++){
cout << vec[i] << flush;
if (i < n-1){
cout << ", " << flush;
}
}
cout << "]" << endl;
}
int main() {
int A[] = {5, 10, 30, 20, 35, 40, 15};
Print(A, sizeof(A)/sizeof(A[0]), "A");
Heapify(A, sizeof(A)/sizeof(A[0]));
Print(A, sizeof(A)/sizeof(A[0]), "Heapified A");
cout << endl;
int B[] = {5, 10, 30, 20};
Print(B, sizeof(B)/sizeof(B[0]), "B");
Heapify(B, sizeof(B)/sizeof(B[0]));
Print(B, sizeof(B)/sizeof(B[0]), "Heapified B");
return 0;
}