-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path..Heap data structure
91 lines (81 loc) · 2.1 KB
/
..Heap data structure
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
#include <iostream>
using namespace std;
class Student {
int marks[10];
int n;
public:
void readMarks();
void displayMarks();
void buildHeap(bool isMaxHeap);
void printExtreme(bool isMax);
};
void Student::readMarks() {
cout << "Enter the number of marks: ";
cin >> n;
cout << "Enter marks: ";
for (int i = 0; i < n; i++) {
cin >> marks[i];
}
}
void Student::displayMarks() {
cout << "Marks: ";
for (int i = 0; i < n; i++) {
cout << marks[i] << " ";
}
cout << endl;
}
void Student::buildHeap(bool isMaxHeap) {
int startIdx = n / 2 - 1;
for (int i = startIdx; i >= 0; i--) {
int current = i;
int child = 2 * i + 1;
if (isMaxHeap) {
while (child < n) {
if (child + 1 < n && marks[child + 1] > marks[child]) {
child++;
}
if (marks[child] > marks[current]) {
swap(marks[child], marks[current]);
current = child;
child = 2 * current + 1;
} else {
break;
}
}
} else {
while (child < n) {
if (child + 1 < n && marks[child + 1] < marks[child]) {
child++;
}
if (marks[child] < marks[current]) {
swap(marks[child], marks[current]);
current = child;
child = 2 * current + 1;
} else {
break;
}
}
}
}
}
void Student::printExtreme(bool isMax) {
if (isMax) {
cout << "Maximum mark: " << marks[0] << endl;
} else {
cout << "Minimum mark: " << marks[0] << endl;
}
}
int main() {
Student s;
s.readMarks();
s.displayMarks();
s.buildHeap(true);
cout << "Building max heap..." << endl;
s.displayMarks();
s.printExtreme(true);
s.buildHeap(false);
cout << "Building min heap..." << endl;
s.displayMarks();
s.printExtreme(false);
return 0;
}