-
Notifications
You must be signed in to change notification settings - Fork 0
/
heap.c
98 lines (80 loc) · 1.96 KB
/
heap.c
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 <stdio.h>
#include <stdlib.h>
typedef struct {
void *reg;
double dist;
} treg;
typedef struct {
treg *vetor;
int tam;
int max;
} theap;
void troca(treg *a, treg *b) {
treg aux = *a;
*a = *b;
*b = aux;
}
int pai(int n) {
return (n - 1) / 2;
}
int filho_esq(int n) {
return (n * 2) + 1;
}
int filho_dir(int n) {
return (n * 2) + 2;
}
void desce(theap *pheap, int n) {
int maior = n;
int esq = filho_esq(n);
int dir = filho_dir(n);
if (esq < pheap->tam && pheap->vetor[esq].dist > pheap->vetor[maior].dist)
maior = esq;
if (dir < pheap->tam && pheap->vetor[dir].dist > pheap->vetor[maior].dist)
maior = dir;
if (maior != n) {
troca(&pheap->vetor[n], &pheap->vetor[maior]);
desce(pheap, maior);
}
}
void constroi_heap(theap *pheap, int max) {
pheap->max = max;
pheap->tam = 0;
pheap->vetor = malloc(sizeof(treg *) * max);
}
void sobe(theap *pheap, int n) {
int p = pai(n);
if (pheap->vetor[p].dist < pheap->vetor[n].dist) {
troca(&pheap->vetor[n], &pheap->vetor[p]);
sobe(pheap, p);
}
}
void altera_prioridade(theap *pheap, int n, void *reg, double dist) {
treg anterior = pheap->vetor[n];
pheap->vetor[n].reg = reg;
pheap->vetor[n].dist = dist;
if (anterior.dist < dist)
sobe(pheap, n);
if (anterior.dist > dist)
desce(pheap, n);
}
void heap_sort(theap *pheap) {
int n = pheap->tam;
for (int i = pheap->tam - 1; i > 0; i--) {
troca(&pheap->vetor[0], &pheap->vetor[i]);
pheap->tam -= 1;
desce(pheap, 0);
}
pheap->tam = n;
}
int insere_elemento(theap *pheap, void *reg, double dist) {
if (pheap->tam == pheap->max)
return EXIT_FAILURE;
pheap->vetor[pheap->tam].reg = reg;
pheap->vetor[pheap->tam].dist = dist;
sobe(pheap, pheap->tam);
pheap->tam += 1;
return EXIT_SUCCESS;
}
void heap_apaga(theap *pheap) {
free(pheap->vetor);
}