-
Notifications
You must be signed in to change notification settings - Fork 0
/
Heap.cpp
110 lines (97 loc) · 1.53 KB
/
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
#include "Heap.h"
#include "iostream"
using namespace std;
int Heap::CreateFromArrayList(ArrayList * al)
{
int i;
length = al->GetLength();
for(i= 0; i < length; i++)
data[i+1] = al->GetElement(i);
for (i = length / 2; i >= 1; i--)
AdjustDown(i);
return 0;
}
int Heap::Delete(int node)
{
if (node<=0 || node >length)
return 1;
else
{
swap(data[length], data[node]);
length--;
AdjustDown(node);
return 0;
}
}
int Heap::Insert(int element)
{
if (length == MAX_SIZE - 1)
return 1;
length++;
data[length] = element;
AdjustUp(length);
return 0;
}
int Heap::GetAndDeleteRoot()
{
if (IsEmpty())
return -1;
int root = data[1];
Delete(1);
return root;
}
int Heap::IsEmpty()
{
return length == 0;
}
int Heap::ShowAll()
{
if (IsEmpty())
cout << "±íΪ¿Õ";
else
{
for (int i = 1; i <= length; i++)
cout << data[i] << " ";
cout << endl;
}
return 0;
}
int Heap::GetLength()
{
return length;
}
Heap::Heap()
{
length = 0;
}
Heap::~Heap()
{
}
void Heap::AdjustDown(int node)
{
int current = node, son = current*2;
int temp = data[current];
while (son<=length)
{
if (son + 1 <= length && data[son + 1] >= data[son])
son++;
if (data[son] <= temp)
break;
data[current] = data[son];
current = son;
son = current * 2;
}
data[current] = temp;
}
void Heap::AdjustUp(int node)
{
int current = node, parent = current / 2;
int temp = data[current];
while (!(current == 1|| temp <= data[parent]))
{
data[current] = data[parent];
current = parent;
parent = current / 2;
}
data[current] = temp;
}