-
Notifications
You must be signed in to change notification settings - Fork 0
/
HeapOperations.cpp
119 lines (103 loc) · 2.46 KB
/
HeapOperations.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
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
#include<iostream>
using namespace std;
#define MAX 20
class Heap{
int arr[MAX];
int size;
public:
Heap(){
size = 0;
}
void insert(int);
void deleteRoot();
int extract_max();
void print();
void heapify(int arr[],int,int);
int getSize();
};
void Heap :: heapify(int arr[],int n,int i){
int curridx = i;
int leftIndex = 2*i + 1 ;
int rightIndex = 2*i + 2 ;
if(leftIndex<n && arr[leftIndex]>arr[curridx]){
curridx = leftIndex;
}
if(rightIndex<n && arr[rightIndex]>arr[curridx]){
curridx = rightIndex;
}
if(curridx!=i){
// Node has reached its correct place
// swap them
swap(arr[curridx],arr[i]);
heapify(arr,n,curridx);
}
}
void Heap :: insert(int val){
// Insert at the last
int index = size;
size += 1;
arr[index] = val;
// Now move the node to its correct position using bottom to top approach
while(index>=0){
int parentIdx = (index-1)/2;
if(arr[index]>arr[parentIdx]){
swap(arr[index],arr[parentIdx]);
index = parentIdx;
}
else{
return;
}
}
}
void Heap :: deleteRoot(){
if(size==0) {
cout << "Nothing to delete";
return ;
}
cout << "Delete called \n";
// get the last element
int lastele = arr[size-1];
// replace the first elemnt with last element
arr[0] = lastele;
// decrement the size
size--;
// Now move the root node to its correct position using heapify method
heapify(arr,size,0);
// Note while deleting the root node the relative positions of its children may change
}
int Heap :: getSize(){
return size;
}
int Heap :: extract_max(){
if(size!=0) return arr[0];
return -1;
}
void Heap :: print(){
for(int i=0;i<size;i++){
cout << arr[i] << " " ;
}
cout << endl;
}
int main(){
Heap heap;
heap.insert(54);
heap.insert(53);
heap.insert(55);
heap.insert(52);
heap.insert(70);
heap.print();
cout << "Heap size : " << heap.getSize()<<endl;
heap.deleteRoot();
heap.print();
heap.deleteRoot();
heap.print();
cout << "Heap size : " << heap.getSize()<<endl;
heap.deleteRoot();
heap.print();
cout << "Max element in heap is : " << heap.extract_max() << endl;
heap.deleteRoot();
heap.deleteRoot();
heap.deleteRoot();
cout << endl;
return 0;
}