Created
July 11, 2017 20:21
-
-
Save CibelePaulinoAndrade/7bbc159c9920bfeaefa268bcf3a83df4 to your computer and use it in GitHub Desktop.
Busca Linear x Binaria
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import random | |
import timeit | |
import matplotlib.pyplot as plt | |
tempLinear = []; tempBinaria = []; tempDifer = []; tempMedLinear = []; tempMedBinaria = [] | |
tam=[6000, 9000, 12000, 15000, 24000] | |
def listaRan(tam, lista): | |
random.seed() | |
i=0; | |
while i<tam: | |
num=random.randint(1,10*tam) | |
if num not in lista: | |
lista.append(num) | |
i+=1 | |
return lista | |
def shellSort(lista): | |
aux = len(lista) // 2 | |
while aux > 0: | |
for i in range(aux, len(lista)): | |
temp = lista[i] | |
j = i | |
while j >= aux and lista[j - aux] > temp: | |
lista[j] = lista[j - aux] | |
j -= aux | |
lista[j] = temp | |
aux //= 2 | |
def listaEsc(lista): | |
aux = random.choice(lista) | |
return aux | |
def pesqLinear(elem, lista): | |
for i in lista: | |
if(i == elem): | |
return True | |
return False | |
def pesqBinaria(elem, lista): | |
esq = 0 | |
direita = len (lista) | |
while 1: | |
meio = (esq+direita)//2 | |
aux = lista[meio] | |
if elem == aux: | |
return True | |
elif elem > aux: | |
esq = meio | |
else: | |
direita = meio | |
return False | |
def timeSearch(elem, lista): | |
auxl = timeit.timeit("pesqLinear({},{})". format(elem, lista),setup="from __main__ import pesqLinear", number=1) | |
auxb = timeit.timeit("pesqBinaria({},{})". format(elem, lista),setup="from __main__ import pesqBinaria", number=1) | |
tempLinear.append(auxl) | |
tempBinaria.append(auxb) | |
def timeMedio (): | |
auxl = 0 | |
auxb = 0 | |
for i in range (10): | |
auxl = tempLinear [i] + auxl | |
auxl = auxl/10 | |
tempLinear [:] = [] | |
for i in range (10): | |
auxb = tempBinaria [i] + auxb | |
auxb = auxb/10 | |
tempBinaria [:] = [] | |
tempMedLinear.append(auxl) | |
tempMedBinaria.append(auxb) | |
def calcDiferenca (): | |
for i in range (5): | |
auxd = tempMedLinear[i] - tempMedBinaria[i] | |
tempDifer.append(auxd) | |
def grafico (): | |
plt.plot(tam, tempMedLinear, label = "Busca Linear") | |
plt.plot(tam, tempMedBinaria, label = "Busca Binária") | |
plt.plot(tam, tempDifer, label = "Diferença") | |
plt.legend() | |
plt.show() | |
listaOriginal=[] | |
for i in tam: | |
print("Gerando lista para o tamanho: ") | |
print(i) | |
listaRan(i, listaOriginal) | |
print("Ordenando lista gerada...") | |
shellSort(listaOriginal) | |
for j in range (10): | |
elem = listaEsc(listaOriginal) | |
print ("Procurando Elemento...") | |
timeSearch(elem, listaOriginal) | |
timeMedio() | |
listaOriginal [:] = [] | |
calcDiferenca() | |
grafico() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment