-
Notifications
You must be signed in to change notification settings - Fork 0
/
HeapSort.cpp
80 lines (65 loc) · 1.54 KB
/
HeapSort.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
#include "HeapSort.h"
#include <ncurses.h>
#include <unistd.h>
void HeapSort::sort() {
for (int i = vect.size() / 2 - 1; i >= 0; --i) {
heapify(vect.size(), i);
}
for (int i = vect.size() - 1; i >= 0; --i) {
swap(0, i);
heapify(i, 0);
}
}
void HeapSort::printSort() {
for (int i = vect.size() / 2 - 1; i >= 0; --i) {
printHeapify(vect.size(), i);
}
for (int i = vect.size() - 1; i >= 0; --i) {
printSwap(0, i);
printHeapify(i, 0);
}
}
void HeapSort::heapify(const int n, const int i) {
int largest = i;
int left = i * 2 + 1;
int right = i * 2 + 2;
if (left < n && vect[left] > vect[largest]) {
largest = left;
}
if (right < n && vect[right] > vect[largest]) {
largest = right;
}
if (largest != i) {
swap(i, largest);
heapify(n, largest);
}
}
void HeapSort::printHeapify(const int n, const int i) {
int largest = i;
int left = i * 2 + 1;
int right = i * 2 + 2;
if (left < n && vect[left] > vect[largest]) {
largest = left;
}
if (right < n && vect[right] > vect[largest]) {
largest = right;
}
if (largest != i) {
printSwap(i, largest);
printHeapify(n, largest);
}
}
void HeapSort::swap(const int index1, const int index2) {
int temp = vect[index1];
vect[index1] = vect[index2];
vect[index2] = temp;
}
void HeapSort::printSwap(const int index1, const int index2) {
refresh();
usleep(10000);
int temp = vect[index1];
vect[index1] = vect[index2];
vect[index2] = temp;
clearPrintBar(index1, vect[index1]);
clearPrintBar(index2, vect[index2]);
}