-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathheap.cpp
More file actions
100 lines (79 loc) · 1.93 KB
/
heap.cpp
File metadata and controls
100 lines (79 loc) · 1.93 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
#include <iostream>
using namespace std;
class heap{
public:
int arr[100];
int size = 0;
void insert(int val){
//in the 0th index of array , we are not filling any thing;
size = size+1;
int index = size;
arr[index] = val;
while(index > 1){
//parent of the node which at index position in the max heap
int parent = index/2; //1 based indexing
if(arr[parent] < arr[index]){
swap(arr[parent], arr[index]);
index = parent;
}
else{
return;
}
}
}
void deletefromHeap(){
if(size == 0){
cout<<"Nothing to delete"<<endl;
return;
}
arr[1] = size;
size--;
int index = 1;
while(index < size){
int left_index = 2*index;
int right_index = 2*index+1;
if(left_index < size && arr[index] < arr[left_index]){
swap(arr[index],arr[left_index]);
index = left_index;
}
else if(right_index < size && arr[index] < arr[right_index]){
swap(arr[index] , arr[right_index]);
index = right_index;
}
else{
return;
}
}
}
void print(){
for(int i = 1; i<=size; i++){
cout<<arr[i]<<" ";
}
cout<<endl;
}
};
int main(){
heap h;
h.insert(55);
h.insert(63);
h.insert(36);
h.insert(45);
h.insert(72);
h.insert(60);
h.print();
h.deletefromHeap();
h.print();
h.deletefromHeap();
h.print();
h.deletefromHeap();
h.print();
h.deletefromHeap();
h.print();
h.deletefromHeap();
h.print();
h.deletefromHeap();
h.print();
h.deletefromHeap();
h.print();
return 0;
}