-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathmin_heap.cpp
More file actions
142 lines (141 loc) · 3.41 KB
/
Copy pathmin_heap.cpp
File metadata and controls
142 lines (141 loc) · 3.41 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
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
#include <bits/stdc++.h>
using namespace std;
//generic implementation of Min Heap using array
template <class T>
struct node
{
T data;
struct node *left;
struct node *right;
};
template <class T>
class MinHeap
{
private:
unsigned int size;
unsigned int capacity;
T *arr;
public:
MinHeap(unsigned int heapsize)
{
capacity = heapsize;
size = 0;
arr = new T[capacity];
}
unsigned int parent(unsigned int i)
{
return (i > 0 ? (i - 1) / 2 : 0);
}
unsigned int leftchild(unsigned int i)
{
unsigned int l = (2 * i) + 1;
return (l < size ? l : size);
}
unsigned int rightchild(unsigned int i)
{
unsigned int r = (2 * i) + 2;
return (r < size ? r : size);
}
T getMin()
{
return (size > 0 ? arr[0] : NULL);
}
void swap(T *x, T *y)
{
T temp = *x;
*x = *y;
*y = temp;
}
void minHeapify(unsigned int rootIndex)
{
unsigned int l = leftchild(rootIndex);
unsigned int r = rightchild(rootIndex);
unsigned int smallest = rootIndex;
if (l < size && arr[l] < arr[rootIndex])
{
smallest = l;
}
if (r < size && arr[r] < arr[smallest])
{
smallest = r;
}
if (smallest != rootIndex)
{
swap(&arr[rootIndex], &arr[smallest]);
minHeapify(smallest);
}
}
T extractMin()
{
if (size <= 0)
{
return NULL;
}
if (size == 1)
{
size--;
return arr[0];
}
T root = arr[0];
arr[0] = arr[--size];
minHeapify(0);
return root;
}
void decrease(unsigned int i, T newVal, bool setToMin = false)
{
arr[i] = newVal;
while (i != 0 && (arr[parent(i)] > arr[i] || setToMin))
{
swap(&arr[i], &arr[parent(i)]);
i = parent(i);
}
}
void remove(unsigned int i)
{
decrease(i, NULL, true);
extractMin();
}
void insert(T k)
{
if (size >= capacity)
{
cout << "\nOverflow: Could not insertKey\n";
return;
}
size++;
int i = size - 1;
arr[i] = k;
while(i != 0 && arr[parent(i)] > arr[i])
{
swap(&arr[i], &arr[parent(i)]);
i = parent(i);
}
}
void traverse()
{
cout << "\n";
for(unsigned int i = 0; i < size; i++)
{
cout << arr[i] << "\n";
}
}
};
int main()
{
MinHeap<int> heap = MinHeap<int>(10);
heap.insert(8);
heap.insert(5);
heap.insert(6);
heap.insert(9);
heap.insert(1);
heap.insert(3);
heap.traverse();
cout << "Min = " << heap.extractMin() << "\n";
heap.traverse();
cout << "Min = " << heap.getMin() << "\n";
heap.remove(3);
heap.traverse();
heap.insert(-2);
heap.traverse();
return 0;
}