-
Notifications
You must be signed in to change notification settings - Fork 0
/
Heap_Insert & Heap_Delete
81 lines (72 loc) · 1.51 KB
/
Heap_Insert & Heap_Delete
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
Using class Keyword it would make a heap class
Time Comlexity is O(logn ) & Space complexity is O(logn)
code->
#include<bits/stdc++.h>
using namespace std;
class Heap{
public:
int arr[100];
int size;
Heap(){
arr[0]=-1;
size=0;
}
// function defined
void insert(int val){
size=size+1;
int index=size;
arr[index]=val;
while(index>1){
int parent=index/2;
// comparing
if(arr[parent]<arr[index]){
swap(arr[parent],arr[index]);
index=parent;
}
else
{
return ;
}
}
}
void DeletefromHeap(){
if(size==0){
return ;
}
arr[1]=arr[size];
size--;
int i=1;
while(i<size){
int leftindex=2*i;
int rightindex=2*i+1;
if(leftindex<size && arr[i]<arr[leftindex]){
swap(arr[i],arr[leftindex]);
i=leftindex;
}
else if(rightindex<size && arr[i]<arr[rightindex]){
swap(arr[i],arr[rightindex]);
i=rightindex;
}
else{
return ;
}
}
}
void print(){
for(int i=1;i<=size;i++){
cout<<arr[i]<<" ";
}
}
};
int main(){
Heap* h=new Heap;
h->insert(50);
h->insert(55);
h->insert(53);
h->insert(52);
h->insert(54);
h->print();
cout<<endl;
h->DeletefromHeap();
h->print();
}