-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathheap.cpp
98 lines (73 loc) · 2.29 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
#include <iostream>
#define N 32
using namespace std;
void troca(int *a, int *b){
int aux;
aux = *a;
*a = *b;
*b = aux;
}
void criaHeap(int v[], int n, int i){
int maior = i;
int esq = 2 * i + 1;
int dir = 2 * i + 2;
if(esq < n && v[esq] > v[maior]){
maior = esq;
}
if(dir < n && v[dir] > v[maior]){
maior = dir;
}
if(maior != i){
troca(&(v[i]), &(v[maior]));
criaHeap(v, n, maior);
}
}
void imprimeArvore(int v[], int n, int i, int level){
if(i < n){
imprimeArvore(v, n, (2*i+2), level+1);
cout << string(level * 5, ' ') << v[i] << endl;
//cout << string(level * 4, ' ') << "|-- " << v[i] << endl;
imprimeArvore(v, n, (2*i+1), level+1);
}
}
void heapSort(int v[], int n){
for(int i = n - 1; i > 0; i--){
cout << "Organiza em Heap:" << endl << endl;
imprimeArvore(v, i+1, 0, 1);
cout << endl << "------------------------------------------------------" << endl << endl;
cout << "Troca os valores " << v[0] << " e " << v[i] << ":" << endl << endl;
troca(&(v[0]), &(v[i]));
imprimeArvore(v, i+1, 0, 1);
cout << endl << "------------------------------------------------------" << endl << endl;
cout << "Remove o " << v[i] << ":" << endl << endl;
imprimeArvore(v, i, 0, 1);
cout << endl << "------------------------------------------------------" << endl << endl;
criaHeap(v, i, 0);
}
}
int main(){
int v[N];
int x, n = 0;
//adicniona valores ao vetor
cout << "Adiciona valores inteiros ao Heap, ate ler o valor 0" << endl;
while(cin >> x && x != 0){
v[n] = x;
n++;
}
cout << "Heap organizado em arvore:" << endl;
imprimeArvore(v, n, 0, 1);
cout << "------------------------------------------------------" << endl
<< "Processo do HeapSort" << endl << endl;
for(int i = n / 2 - 1; i >= 0; i--)
criaHeap(v, n, i);
heapSort(v, n);
cout << "Vetor Organizado {";
for(int i = 0; i < n; i++){
cout << v[i];
if(i < n-1)
cout << ", ";
}
cout <<"}" << endl << endl;
cout << "Arvore do Heap:" << endl << endl;
imprimeArvore(v, n, 0, 1);
}