-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTR5_536281.c
More file actions
77 lines (62 loc) · 1.72 KB
/
TR5_536281.c
File metadata and controls
77 lines (62 loc) · 1.72 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
#include <stdio.h>
#include <stdlib.h>
#include "heap.h"
//Função para fazer a criação da heap e alocar o espaço necessário para ela e para o vetor de elementos da heap
HEAP* HEAP_create(int n, COMP* compara) {
HEAP* heap = malloc(sizeof(HEAP));
heap->N = n;
heap->P = 0;
heap->elems = malloc(n * sizeof(void*));
heap->comparador = compara;
return heap;
}
//Função para adicionar um elemento na heap e fazer a ordenação da heap
void HEAP_add(HEAP* heap, void* elem) {
if (heap->P == heap->N) {
printf("Heap cheio!\n");
return;
}
if (heap->P == 0) {
heap->elems[0] = elem;
heap->P++;
return;
}
int parent = heap->P;
heap->elems[parent] = elem;
while (heap->comparador(heap->elems[parent], heap->elems[(parent - 1) / 2]) == 1) {
void* aux = heap->elems[parent];
heap->elems[parent] = heap->elems[(parent - 1) / 2];
heap->elems[(parent - 1) / 2] = aux;
parent = (parent - 1) / 2;
}
heap->P++;
}
//Função para remover o elemento da heap e fazer a reordenação da heap
void* HEAP_remove(HEAP* heap) {
if (heap->P == 0) {
printf("Heap vazio!\n");
return NULL;
}
void* minimum = heap->elems[0];
heap->elems[0] = heap->elems[heap->P - 1];
heap->P--;
int parent = 0;
int child = 1;
while (child < heap->P) {
if (child + 1 < heap->P) {
if (heap->comparador(heap->elems[child], heap->elems[child + 1]) == -1) {
child++;
}
}
if (heap->comparador(heap->elems[parent], heap->elems[child]) == -1) {
void* aux = heap->elems[parent];
heap->elems[parent] = heap->elems[child];
heap->elems[child] = aux;
parent = child;
child = 2 * parent + 1;
} else {
break;
}
}
return minimum;
}