1
+ /* ************************************************************
2
+ * File: pqueue-heap.cpp
3
+ *
4
+ * Implementation file for the HeapPriorityQueue
5
+ * class.
6
+ */
7
+
8
+ #include " pqueue-heap.h"
9
+ #include " error.h"
10
+
11
+ HeapPriorityQueue::HeapPriorityQueue () {
12
+ capacity = INITIAL_CAPACITY;
13
+ count = 0 ;
14
+ array = new string[capacity];
15
+ }
16
+
17
+ HeapPriorityQueue::~HeapPriorityQueue () {
18
+ delete[] array;
19
+ }
20
+
21
+ int HeapPriorityQueue::size () {
22
+ return count;
23
+ }
24
+
25
+ bool HeapPriorityQueue::isEmpty () {
26
+ return count == 0 ;
27
+ }
28
+
29
+ void HeapPriorityQueue::enqueue (string value) {
30
+ if (count == capacity) expandCapacity ();
31
+ array[count] = value;
32
+ count++;
33
+ if (count > 1 ) bubbleup (count);
34
+ }
35
+
36
+ string HeapPriorityQueue::peek () {
37
+ if (isEmpty ()) error (" peek: Attempting to peek into an empty pqueue" );
38
+ return array[0 ];
39
+ }
40
+
41
+ string HeapPriorityQueue::dequeueMin () {
42
+ if (isEmpty ()) error (" dequeueMin: Attempting to dequeue and empty pqueue" );
43
+ string first = array[0 ];
44
+ array[0 ] = array[count - 1 ];
45
+ count--;
46
+ if (count > 1 ) bubbledown (1 ); // bubbledown first element
47
+ return first;
48
+ }
49
+
50
+ void HeapPriorityQueue::expandCapacity () {
51
+ string *oldArray = array;
52
+ capacity *= 2 ;
53
+ array = new string[capacity];
54
+ for (int i = 0 ; i < count; i++) {
55
+ array[i] = oldArray[i];
56
+ }
57
+ delete[] oldArray;
58
+ }
59
+
60
+ void HeapPriorityQueue::bubbleup (int index) {
61
+ if (array[index - 1 ] < array[(index / 2 ) - 1 ]) {
62
+ string temp = array[index - 1 ];
63
+ array[index - 1 ] = array[(index / 2 ) - 1 ];
64
+ array[(index / 2 ) - 1 ] = temp;
65
+ if (index / 2 - 1 >= 1 ) bubbleup (index / 2 );
66
+ }
67
+ }
68
+
69
+ void HeapPriorityQueue::bubbledown (int index) {
70
+ if (count > (2 * index ) - 1 && array[index - 1 ] > array[(2 * index ) - 1 ]) {
71
+ string temp = array[index - 1 ];
72
+ array[index - 1 ] = array[(2 * index ) - 1 ];
73
+ array[(2 * index ) - 1 ] = temp;
74
+ bubbledown (2 * index );
75
+ }
76
+
77
+ if (count > 2 * index && array[index - 1 ] > array[2 * index ]) {
78
+ string temp = array[index - 1 ];
79
+ array[index - 1 ] = array[2 * index ];
80
+ array[2 * index ] = temp;
81
+ bubbledown (2 * index + 1 );
82
+ }
83
+ }
0 commit comments