-
Notifications
You must be signed in to change notification settings - Fork 0
/
heapBinary.cpp
113 lines (96 loc) · 1.92 KB
/
heapBinary.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
#include "heapBinary.h"
int BinaryHeap::parent(int index)
{
return (index - 1) / 2;
}
int BinaryHeap::leftChild(int index)
{
return 2*index + 1;
}
int BinaryHeap::rightChild(int index)
{
return 2*index + 2;
}
void BinaryHeap::heapifyUp(int index)
{
while (index > 0 && heap[index] > heap[parent(index)]) {
swap(heap[index], heap[parent(index)]);
index = parent(index);
}
}
void BinaryHeap::maxHeapify(int size, int index)
{
int maxIndex = index;
int left = leftChild(index);
int right = rightChild(index);
if (index < 0) return;
if (right < size && heap[right] > heap[maxIndex]) {
maxIndex = right;
}
if (left < size && heap[left] > heap[maxIndex]) {
maxIndex = left;
}
if (maxIndex != index) {
swap(heap[maxIndex], heap[index]);
maxHeapify(size, maxIndex);
}
}
void BinaryHeap::resize(int newCapacity)
{
}
BinaryHeap::BinaryHeap()
{
size = 0;
capacity = 16;
heap = new int[capacity];
}
BinaryHeap::~BinaryHeap()
{
delete[] heap;
}
void BinaryHeap::enqueue(int value)
{
heap[size++] = value;
heapifyUp(size - 1);
}
int BinaryHeap::dequeue()
{
int value = heap[0];
heap[0] = heap[--size];
maxHeapify(size, 0);
return value;
}
void BinaryHeap::display()
{
for (int i = 0; i < size; i++) {
cout << heap[i] << " ";
}
cout << endl;
}
void BinaryHeap::heapSort()
{
int n = size;
for (int i = n - 1; i >= 0; i--) {
swap(heap[0], heap[i]);
maxHeapify(i, 0);
}
}
bool BinaryHeap::binarySearch(int value)
{
heapSort();
int left = 0;
int right = size - 1;
while (left <= right) {
int mid = left + (right - left) / 2;
if (heap[mid] == value) {
return true;
}
if (heap[mid] < value) {
left = mid + 1;
}
else {
right = mid - 1;
}
}
return false;
}