Skip to content

Commit 79b0bb6

Browse files
authored
Add files via upload
1 parent 45e80d6 commit 79b0bb6

File tree

1 file changed

+88
-0
lines changed

1 file changed

+88
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,88 @@
1+
#include <iostream>
2+
3+
using namespace std;
4+
5+
void swap(int A[], int i, int j){
6+
int temp = A[i];
7+
A[i] = A[j];
8+
A[j] = temp;
9+
}
10+
11+
int Delete(int A[], int n){
12+
int x = A[0]; // Max element
13+
A[0] = A[n-1];
14+
15+
int i = 0;
16+
int j = 2 * i + 1;
17+
18+
while (j < n-1){
19+
// Compare left and right children
20+
if (A[j] < A[j+1]){
21+
j = j+1;
22+
}
23+
24+
// Compare parent and largest child
25+
if (A[i] < A[j]){
26+
swap(A, i, j);
27+
i = j;
28+
j = 2 * i + 1;
29+
} else {
30+
break;
31+
}
32+
}
33+
return x;
34+
}
35+
36+
void Heapify(int A[], int n){
37+
// # of leaf elements: (n+1)/2, index of last leaf element's parent = (n/2)-1
38+
for (int i=(n/2)-1; i>=0; i--){
39+
40+
int j = 2 * i + 1; // Left child for current i
41+
42+
while(j < n-1){
43+
// Compare left and right children of current i
44+
if (A[j] < A[j+1]){
45+
j = j+1;
46+
}
47+
48+
// Compare parent and largest child
49+
if (A[i] < A[j]){
50+
swap(A, i, j);
51+
i = j;
52+
j = 2 * i + 1;
53+
} else {
54+
break;
55+
}
56+
}
57+
}
58+
}
59+
60+
template <class T>
61+
void Print(T& vec, int n, string s){
62+
cout << s << ": [" << flush;
63+
for (int i=0; i<n; i++){
64+
cout << vec[i] << flush;
65+
if (i < n-1){
66+
cout << ", " << flush;
67+
}
68+
}
69+
cout << "]" << endl;
70+
}
71+
72+
int main() {
73+
74+
int A[] = {5, 10, 30, 20, 35, 40, 15};
75+
Print(A, sizeof(A)/sizeof(A[0]), "A");
76+
77+
Heapify(A, sizeof(A)/sizeof(A[0]));
78+
Print(A, sizeof(A)/sizeof(A[0]), "Heapified A");
79+
cout << endl;
80+
81+
int B[] = {5, 10, 30, 20};
82+
Print(B, sizeof(B)/sizeof(B[0]), "B");
83+
84+
Heapify(B, sizeof(B)/sizeof(B[0]));
85+
Print(B, sizeof(B)/sizeof(B[0]), "Heapified B");
86+
87+
return 0;
88+
}

0 commit comments

Comments
 (0)