-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathHeap.cpp
More file actions
73 lines (63 loc) · 1.73 KB
/
Heap.cpp
File metadata and controls
73 lines (63 loc) · 1.73 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
/*
* Title: Heaps, Priority Queues
* Author: Berk Temel
* ID: 22002675
* Section: 2
* Assignment: 3
* Description: Implementation of Heap class, from lecture slides
*/
#include "Heap.h"
Heap::Heap() {
size = 0;
}
bool Heap::heapIsEmpty() const {
return size == 0;
}
void Heap::heapInsert(const KeyedItem &newItem) {
if (size >= MAX_HEAP)
return;
items[size] = newItem;
size++;
heapRebuild(0);
}
void Heap::heapDelete(KeyedItem &rootItem) {
if (heapIsEmpty())
return;
else {
rootItem = items[0];
items[0] = items[size - 1];
size--;
heapRebuild(0);
}
}
void Heap::heapRebuild(int root) {
int child = 2 * root + 1; // index of root's left child, if any
if ( child < size ) {
// root is not a leaf so that it has a left child
int rightChild = child + 1; // index of a right child, if any
// If root has right child, find larger child
if ((rightChild < size) &&
(items[rightChild] > items[child]))
child = rightChild; // index of larger child
// If root’s item is smaller than larger child, swap values
if (items[root] < items[child]) {
KeyedItem temp = items[root];
items[root] = items[child];
items[child] = temp;
// transform the new subtree into a heap
heapRebuild(child);
}
}
}
bool Heap::heapFull() const {
return size >= MAX_HEAP;
}
void Heap::heapPeek(KeyedItem &topItem) {
topItem = items[0];
}
void Heap::heapChange(int time) {
for(int i = 0; i < size; i++) {
items[i].setCurrentTime(time);
}
heapRebuild(0);
}