-
Notifications
You must be signed in to change notification settings - Fork 0
/
heap.cpp
118 lines (103 loc) · 1.88 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
111
112
113
114
115
116
117
118
//max heap and heapsort......
#include<iostream>
#include<algorithm>
#include<vector>
#include<climits>
using namespace std;
class heapme {
int temp, n;
vector<int> heap;
public:
heapme() {
heap.push_back(INT_MAX);
n = 0;
}
void insertion(int item) {
heap.push_back(item);
n++;
heapifyup(n);
}
void heapifyup(int k) {
if (k>0) {
if (heap[k] > heap[k/2]) {
temp = heap[k];
heap[k] = heap[k/2];
heap[k/2] = temp;
heapifyup(k/2);
}
}
return;
}
int search(int item) {
for (int i = 1; i <= n; i++) {
if (item == heap[i])
return i;
}
return 0;
}
void deletion(int item) {
int pos = search(item);
if (pos != 0) {
heap[pos] = heap[n];
n--;
heapifydown(pos);
}
else
cout << "\nelement not present!!!";
return;
}
void heapifydown(int i) {
int left = 2 * i, right = 2 * i + 1, ptr;
if (left <= n) {
if (heap[right] > heap[left] && right <= n)
ptr = right;
else if (heap[right] > heap[left] && right <= n)
ptr = left;
else
ptr = left;
if (heap[i] < heap[ptr]) {
temp = heap[i];
heap[i] = heap[ptr];
heap[ptr] = temp;
heapifydown(ptr);
}
return;
}
}
void display() {
for (int i = 1; i <= n; i++) {
cout << heap[i] << "\t";
}
cout << "\n";
}
void heapsort(vector<int>& arr) {
for (int i = 0; i <arr.size(); i++) {
insertion(arr[i]);
}
int j = n;
while (j>0) {
arr[j - 1] = heap[1];
deletion(heap[1]);
j--;
}
}
};
int main() {
int i;
heapme h1;
vector<int> arr;
int ch = 1;
while (ch == 1) {
cout << "\nenter the element:";
cin >> i;
arr.push_back(i);
cout << "\nwant to enter more:(1/0):";
cin >> ch;
}
h1.heapsort(arr);
for (int i = 0; i < arr.size(); i++) {
cout << (arr[i]) << "\t";
}
cin >> i;
return 0;
}