-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathHeap
More file actions
54 lines (45 loc) · 1.23 KB
/
Heap
File metadata and controls
54 lines (45 loc) · 1.23 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
using namespace std;
void heapify(Movie_Vertex * arr, int x, int j);
void createHeap(Movie_Vertex * arr, int x);
int main() {
vector < Movie_Vertex > ex;
for (int i = 0; i < 50; i++) {
string movie = "Movie ";
Movie_Vertex a(movie.append(to_string(i + 1)), "Horror", 1 + ((double) rand() / RAND_MAX) * 9);
ex.push_back(a);
}
Movie_Vertex * arr[ex.size()];
for (int i = 0; i < ex.size(); i++) {
arr[i] = & ex.at(i);
}
for (int i = 0; i < sizeof(arr) / sizeof(arr[0]); i++) {
cout << arr[i] -> getTitle() << " ";
}
createHeap( * arr, 25);
cout << " HEAP CREATED " << endl;
for (int i = 0; i < sizeof(arr) / sizeof(arr[0]); i++) {
cout << arr[i] -> getTitle() << " ";
}
return 0;
}
void heapify(Movie_Vertex * arr, int x, int j) {
int max = j;
int left = 2 * j + 1;
int right = 2 * j + 2;
if (arr[left].getRating() > arr[max].getRating() && left < x) {
max = left;
}
if (arr[right].getRating() > arr[max].getRating() && right < x) {
max = right;
}
if (max != j) {
swap(arr[j], arr[max]);
heapify(arr, x, max);
}
}
void createHeap(Movie_Vertex * arr, int x) {
int firstIndex = (x / 2) - 1;
for (int j = firstIndex; j >= 0; j--) {
heapify(arr, x, j);
}
}