-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathheap.cc
More file actions
126 lines (101 loc) · 1.59 KB
/
heap.cc
File metadata and controls
126 lines (101 loc) · 1.59 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 <cstdlib>
#include <ctime>
using namespace std;
int PARENT(int i){
return (i-1)/2;
}
int LEFT(int i){
return 2*i+1;
}
int RIGHT(int i){
return 2*(i+1);
}
void swap(int& x, int& y){
int temp = x;
x = y;
y = temp;
}
void Heapify(int* A, int n, int i){
int l = LEFT(i);
int r = RIGHT(i);
//cout << l << " " << r << endl;
int min = i;
//cout << n << " ";
if(l<n && A[min]>A[l]){
min = l;
}
if(r<n && A[min]>A[r]){
min = r;
}
if(min!=i){
swap(A[min],A[i]);
Heapify(A,n,min);
}
}
void Build_Heap(int* A, int n){
for(int i=n/2-1;i>=0;i--){
Heapify(A,n,i);
}
}
int Heap_Min(int* A){
return A[0];
}
void Extract_Min(int* A, int& n){
if(n<1){
cout << "Error: Underflow";
}
else{
int min = A[0];
A[0] = A[n-1];
n = n-1;
Heapify(A, n, 0);
}
}
void Update(int* A, int n, int i, int key){
if(key < A[i]){
A[i] = key;
while(i>1 && A[PARENT(i)]>A[i]){
swap(A[i],A[PARENT(i)]);
i = PARENT(i);
}
}
}
void Insert(int* A, int& n, int x){
n = n+1;
A[n-1] = 9999;
Update(A,n,n-1,x);
}
int main(){
int n;
cout << "Enter the size of array: ";
cin >> n;
int A[n];
srand(time(NULL));
for(int i=0;i<n;i++){
A[i] = rand()%100+1;
}
for(int i=0;i<n;i++){
cout << A[i] << " ";
}
cout << endl;
Build_Heap(A,n);
for(int i=0;i<n;i++){
cout << A[i] << " ";
}
cout << endl;
Extract_Min(A,n);
for(int i=0;i<n;i++){
cout << A[i] << " ";
}
cout << endl;
cout << "Enter a no. to insert into heap: ";
int x;
cin >> x;
Insert(A,n,x);
for(int i=0;i<n;i++){
cout << A[i] << " ";
}
cout << endl;
}
//"A[" << i << "] = " <<