-
Notifications
You must be signed in to change notification settings - Fork 0
/
t_heap.cpp
129 lines (111 loc) · 2.03 KB
/
t_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
//max t-heap
#include<iostream>
#include<vector>
using namespace std;
class theap {
int k;
vector<int> heap;
public:
theap(int k) {
this->k = k;
}
void insertion(int item) {
heap.push_back(item);
heapifyup(heap.size() - 1);
return;
}
void heapifyup(int i) {
if (i<0) {
return;
}
int par = (i - 1) / k;
if (heap[par] < heap[i]) {
swap(heap[par], heap[i]);
heapifyup(par);
}
return;
}
int search(int item, int index) {
if (item > heap[index]) {
return -1;
}
else if (item == heap[index]) {
return index;
}
else {
for (int i = 1; i <= k; i++) {
if ((k*index + i) > heap.size()) {
return -1;
}
if (search(item, (k*index + i)) > -1)
return search(item, (k*index + i));
}
return -1;
}
}
void display() {
cout << "\n";
for (int i = 0; i < heap.size(); i++) {
cout << heap[i] << "\t";
}
}
void deletion(int item) {
int pos = search(item, 0);
if (pos == -1) {
cout << "\nitem not found.\n";
return;
}
heap[pos] = heap[heap.size() - 1];
heap.pop_back();
heapifydown(pos);
}
void heapifydown(int pos) {
if ((k*pos + 1) > heap.size()) {
return;
}
int ptr = k*pos + 1;
for (int i = 2; i <= k; i++) {
int j = k*pos + i;
if (j < heap.size()) {
if (heap[j] > heap[ptr]) {
ptr = j;
}
}
}
if (heap[ptr] > heap[pos]) {
swap(heap[ptr], heap[pos]);
heapifydown(ptr);
}
return;
}
void heapsort() {
vector<int> arr;
while (!heap.empty()) {
arr.push_back(heap[0]);
deletion(heap[0]);
}
cout << "\n";
for (int i = 0; i<arr.size(); i++) {
cout << arr[i] << "\t";
}
}
};
int main() {
theap h1(2);
h1.insertion(10);
h1.insertion(7);
h1.insertion(9);
h1.insertion(8);
h1.insertion(4);
h1.insertion(5);
h1.display();
h1.insertion(11);
h1.display();
h1.insertion(6);
h1.display();
h1.deletion(11);
h1.display();
h1.heapsort();
system("pause");
return 0;
}