-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathBinaryHeap.cpp
134 lines (100 loc) · 2.05 KB
/
BinaryHeap.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
133
134
#include<iostream>
#include<climits>
#include "BinaryHeap.h"
using namespace std;
void swap(Node **x, Node **y);
Edge::Edge(Node* tail, Node* head, double length)
{
this->tail = tail;
this->head = head;
this->length = length;
}
Node::Node(int data, int key)
{
this->key = key;
this->data = data;
next = NULL;
state = UNLABELED;
}
Node::Node()
{
next = NULL;
state = UNLABELED;
}
void Node::addIncomingEdge(Edge * edge)
{
incomingEdges.push_back(edge);
}
void Node::addOutgoingEdge(Edge * edge)
{
outgoingEdges.push_back(edge);
}
MinHeap::MinHeap(int cap)
{
heap_size = 0;
capacity = cap;
harr = new Node*[cap];
}
void MinHeap::insertKey(Node * k)
{
if (heap_size == capacity)
{
cout << "\nOverflow: Could not insertKey\n";
return;
}
heap_size++;
int i = heap_size - 1;
harr[i] = k;
while (i != 0 && harr[parent(i)]->key > harr[i]->key)
{
swap(&harr[i], &harr[parent(i)]);
i = parent(i);
}
}
void MinHeap::decreaseKey(int new_val, Node * node)
{
int i;
node->key = new_val;
for(i = 0; i < capacity; i++){
if(harr[i] == node) break;
}
while( i != 0 && harr[parent(i)]->key > harr[i]->key){
swap(&harr[i], &harr[parent(i)]);
i = parent(i);
}
}
Node* MinHeap::extractMin()
{
if (heap_size <= 0)
return NULL;
if (heap_size == 1)
{
heap_size--;
return harr[0];
}
Node* root = harr[0];
harr[0] = harr[heap_size-1];
heap_size--;
MinHeapify(0);
return root;
}
void MinHeap::MinHeapify(int i)
{
int l = left(i);
int r = right(i);
int smallest = i;
if (l < heap_size && harr[l]->key < harr[i]->key)
smallest = l;
if (r < heap_size && harr[r]->key < harr[smallest]->key)
smallest = r;
if (smallest != i)
{
swap(&harr[i], &harr[smallest]);
MinHeapify(smallest);
}
}
void swap(Node ** x, Node ** y){
Node * temp = *x;
*x = *y;
*y = temp;
}