-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathheap.cpp
More file actions
132 lines (119 loc) · 2.65 KB
/
Copy pathheap.cpp
File metadata and controls
132 lines (119 loc) · 2.65 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
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
#include <stdio.h>
#include <stdlib.h>
struct Heap
{
static const int max = 8191;
int array[max+1];
int count;
Heap()
{
count = 0;
}
int left(int x) { return 2 * x; }
int right(int x) { return 2*x+1;}
int parent(int x) { return x/2;}
int size() { return count; }
bool search(int v, int pos = 1)
{
if (pos > count) return false;
if (array[pos] == v) return true;
if (array[pos] > v) return false;
if (search(v, left(pos))) return true;
return search(v, right(pos));
}
void insert(int v)
{
count++;
int pos = count;
while (pos > 1) {
int ppos = parent(pos);
if (array[ppos] < v)
{
array[pos] = v;
return;
} else {
array[pos] = array[ppos];
pos = ppos;
}
}
if (pos == 1) {
array[1] = v;
}
}
int get()
{
return array[1];
}
void remove()
{
int v = array[count];
count--;
int pos = 1;
while(1) {
int l = left(pos);
int r = right(pos);
int next = l;
if (l > count) break;
if ((r <= count) && (array[r] < array[l])) {
next = r;
}
if (v < array[next]) {
break;
} else {
array[pos] = array[next];
pos = next;
}
}
array[pos] = v;
}
void percolate_down(int pos)
{
while (pos < count) {
int l = left(pos);
int r = right(pos);
int next = l;
if (l > count) return;
if ((r <= count) && (array[r] < array[l])) next = r;
if (array[pos] <= array[next]) return;
int tmp = array[pos];
array[pos] = array[next];
array[next] = tmp;
pos = next;
}
}
void build(int* arr, int len)
{
while (count < len) {
count++;
array[count] = arr[count-1];
}
for (int i = count/2; i > 0; i--) {
percolate_down(i);
}
}
};
int main()
{
srand(MAX);
/*
Heap h;
for (int i = 0; i < MAX; i++) {
h.insert(rand()%10000);
}
while(h.size() > 0) {
printf("%.8d\n", h.get());
h.remove();
}
*/
int arr[MAX];
for (int i = 0; i < MAX; i++) {
arr[i] = rand()%10000;
}
Heap h;
h.build(arr, MAX);
while (h.size() > 0) {
printf("%.8d\n", h.get());
h.remove();
}
return 0;
}