-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathheap_sort.cpp
More file actions
135 lines (98 loc) · 2.23 KB
/
heap_sort.cpp
File metadata and controls
135 lines (98 loc) · 2.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
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
130
131
132
133
134
135
#include<iostream>
using namespace std;
struct Vector{
Vector(int array[], int size);
int size;
int capacity;
int * data;
int at(int index);
void print_vector();
void free_vector();
};
void heap_sort(Vector vector);
void percolate(Vector vector, int last_index);
int main(){
int array [] = {2, 20, 1, 7, 8, 9, 12, 6, 30};
Vector vector(array, 9);
vector.print_vector();
heap_sort(vector);
vector.print_vector();
vector.free_vector();
}
void heap_sort(Vector vector){
// need to percolate and then switch
for(int i = vector.size - 1; i > 0; --i){
percolate(vector, i);
int temp = vector.data[i];
vector.data[i] = vector.data[0];
vector.data[0] = temp;
vector.print_vector();
}
}
void percolate(Vector vector, int last_index){
int j = 0;
do {
if(vector.data[j] == -10){
return;
}
vector.print_vector();
int left_child = 2*j + 1;
int right_child = 2*j + 2;
if(left_child <= last_index && right_child <= last_index){
if(vector.data[left_child] > vector.data[right_child]){
if(vector.data[j] < vector.data[left_child]){
int temp = vector.data[j];
vector.data[j] = vector.data[left_child];
vector.data[left_child] = temp;
j = left_child;
} else {
return;
}
} else {
if(vector.data[j] < vector.data[right_child]){
int temp = vector.data[j];
vector.data[j] = vector.data[right_child];
vector.data[right_child] = temp;
j = right_child;
} else {
return;
}
}
} else if(left_child <= last_index){
if(vector.data[j] < vector.data[left_child]){
int temp = vector.data[j];
vector.data[j] = vector.data[left_child];
vector.data[left_child] = temp;
j = left_child;
} else {
return;
}
} else {
return;
}
} while(j <= last_index);
}
Vector::Vector(int array[], int size){
this->size = size;
this->capacity = size*2;
this->data = new int[capacity];
for(int i = 0; i < capacity; ++i){
if(i < size){
this->data[i] = array[i];
} else {
this->data[i] = -10;
}
}
}
int Vector::at(int index){
return this->data[index];
}
void Vector::print_vector(){
for(int i = 0; i < this->size; ++i){
cout << this->data[i] << " ";
}
cout << endl;
}
void Vector::free_vector(){
delete [] this->data;
}