diff --git a/BinaryHeap b/BinaryHeap new file mode 100644 index 0000000000000000000000000000000000000000..91d02d2756ce2ac41719bcd6823b4b27b0aaa402 --- /dev/null +++ b/BinaryHeap @@ -0,0 +1,63 @@ +from math import log, ceil + +def subir(vetor): + i = len(vetor) - 1 + while i != 0: + if vetor[i] != None: + if vetor[i] < vetor[(i-1)//2]: + vetor[i],vetor[(i-1)//2] = vetor[(i-1)//2],vetor[i] + i = i-1 + +#________________________________________________________________ + +def descer(vetor, inicio = 0): + + while 2*inicio + 1 < len(vetor): + if vetor[2*inicio + 2] == None: + if vetor[2*inicio + 1] < vetor[inicio]: + vetor[2*inicio + 1], vetor[inicio] = vetor[inicio], vetor[2*inicio + 1] + elif vetor[2*inicio + 1] < vetor[2*inicio + 2]: + if vetor[2*inicio + 1] < vetor[inicio]: + vetor[2*inicio + 1], vetor[inicio] = vetor[inicio], vetor[2*inicio + 1] + else: + if vetor[2*inicio + 2] < vetor[inicio]: + vetor[2*inicio + 2], vetor[inicio] = vetor[inicio], vetor[2*inicio + 2] + inicio = inicio + 1 + +#__________________________________________________________________ + +def heapficar(vetor): + pos = (len(vetor) - 1) + inicio = (pos - 1)//2 + + while inicio >= 0: + descer(vetor, inicio) + print(inicio) + inicio = (inicio -1)//2 + +#____________________________________________________________________________________________ + +def realocar(vetor): + altura = ceil(log(len(vetor)+1,2)) - 1 + size = 2**(altura+1)-1 + aux = [None]*size + i = 0 + for item in vetor: + aux[i] = item + i = i+1 + + return aux +#__________________________________________________________________ + +vetor_heap = [23, 12, 9 , 5, 43, 3] + + + +vetor_heap = realocar(vetor_heap) + +print(len(vetor_heap)) +print(vetor_heap) +heapficar(vetor_heap) +print(vetor_heap) + +