-
Notifications
You must be signed in to change notification settings - Fork 0
/
Min_Heap.cpp
133 lines (130 loc) · 2.06 KB
/
Min_Heap.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
#include <iostream>
#include <algorithm>
using namespace std;
class MinHeap
{
private:
int* data;
int sz;
int capacity;
protected:
void swim(int index);
void sink(int index);
public:
MinHeap(int _cap);
~MinHeap();
void push(const int val);
void pop();
int top() const;
int size() const;
void printHeap() const;
};
void MinHeap::swim(int index)
{
while (data[index] < data[(index - 1) / 2] && index>0)
{
swap(data[index], data[(index - 1) / 2]);
index = (index - 1) / 2;
}
}
void MinHeap::sink(int index)
{
int par = index;
while (2 * par + 1 < sz)
{
int son = 2 * par + 1;//index的左子节点
if (son < sz - 1 && data[son + 1] < data[son])
{
++son;
}
if (data[par] < data[son])
{
break;
}
swap(data[par], data[son]);
par = son;
}
}
MinHeap::MinHeap(int _cap) :
sz(0),
capacity(_cap)
{
data = new int[capacity];
}
MinHeap::~MinHeap()
{
delete[]data;
}
void MinHeap::push(const int val)
{
if (sz == capacity)
{
cout << "Full!" << endl;
return;
}
data[sz] = val;
swim(sz);
sz++;
cout << "Push success. Heap size: " << sz << endl;
}
void MinHeap::pop()
{
if (sz == 0)
{
cout << "Empty!" << endl;
return;
}
swap(data[0], data[sz - 1]);
--sz;
sink(0);
cout << "Pop success. Heap size: " << sz << endl;
}
int MinHeap::top() const
{
if (sz == 0)
{
cout << "Empty!" << endl;
return -1;
}
return data[0];
}
int MinHeap::size() const
{
return sz;
}
void MinHeap::printHeap() const
{
if (sz == 0)
{
cout << "Empty!" << endl;
return;
}
cout << "Heap: ";
for (int i = 0; i < sz; i++)
{
cout << data[i] << " ";
}
cout << endl;
}
int main()
{
int _cap;
cout << "请输入所需小顶堆大小" << endl;
cin >> _cap;
MinHeap heap = MinHeap(_cap);
cout << "请输入数据" << endl;
int val;
cout << "Pushing" << endl;
while (scanf("%d", &val) != EOF)
{
heap.push(val);
heap.printHeap();
}
cout << "Popping..." << endl;
while (heap.top() > 0)
{
heap.pop();
heap.printHeap();
}
return 0;
}