-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathMaxHeap.cpp
132 lines (119 loc) · 2.38 KB
/
MaxHeap.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
120
121
122
123
124
125
126
127
128
129
130
131
132
//This file conatains the implementation of maxHeap functions
#include "MaxHeap.h"
//constructor
MaxHeap::MaxHeap(int capacity)
{
arr = new int[capacity]; // create an array with size capacity
this->capacity = capacity;
this->size = 0; //initalise size to zero
}
int MaxHeap::getSize()
{
return size;
}
int MaxHeap::parent(int child)
{
if(child % 2 == 0)
return (child /2) -1;
else
return (child/2);
}
int MaxHeap::left(int parent)
{
return (2 * parent +1);
}
int MaxHeap::right(int parent)
{
return (2 * parent +2);
}
void MaxHeap::siftup(int i)
{
if(i == 0)
return; //only one element in the array
int parent_index = parent(i); // get the index of the parent
if(arr[parent_index] < arr[i])
{
int temp = arr[parent_index]; //if value at parent index is less than inserted value
arr[parent_index] = arr[i]; // swap the values
arr[i] = temp;
siftup(parent_index); // loop untill it satisfies parent child max heap relationship
}
}
void MaxHeap::insert(int k)
{
arr[size] = k; // insert the value into array
siftup(size);
size++; //increment the size of the array
for(int i = 0;i<size;i++)
{
cout<<arr[i]<<" ";
}
cout<<endl;
}
int MaxHeap::getMax()
{
for(int i = 0;i<size;i++)
{
cout<<arr[i]<<" ";
}
cout<<endl;
return arr[0]; // maximum value will be at index 0
}
bool MaxHeap::isLeaf(int i)
{
if(i>=size)
return true;
return false;
}
void MaxHeap::siftdown(int i)
{
int l = left(i);
int r = right(i);
if(isLeaf(l))
return;
int maxIndex = i;
if(arr[l] > arr[i])
{
maxIndex = l;
}
if(!isLeaf(r) && (arr[r] > arr[maxIndex]))
{
maxIndex = r;
}
if(maxIndex != i)
{
int temp = arr[i];
arr[i] = arr[maxIndex];
arr[maxIndex] = temp;
siftdown(maxIndex);
}
}
int MaxHeap::extractMax()
{
int max = arr[0];
arr[0] = arr[size - 1];
size--;
siftdown(0);
return max;
}
void MaxHeap::heapify(int *array, int len)
{
size = len;
arr = array;
for(int i=size-1; i>=0; --i)
{
siftdown(i);
}
}
int MaxHeap::removeAt(int k)
{
int r = arr[k];
arr[k] = arr[size -1]; // replace with rightmost leaf
size-- ;
int p = parent(k);
if(k == 0 || arr[k] < arr[p])
siftdown(k);
else
siftup(k);
return r;
}