Apuntes_Python/05_diez_proyectos/06-binary_search/busqueda_binaria.py
2022-12-24 22:41:20 -03:00

68 lines
2.1 KiB
Python

# Implementacion algoritmo de búsqueda binaria
# Demostración de velocidad de busqueda respecto a busqueda 'Simple'
import random
import time
# Búsqueda Simple:
def busqueda_simple(l, target):
"""
Lee la lista completa para encontrar el item objetivo comparando
cada item de la lista con este, devolviendo.
El indice, si lo encuentra.
-1, si no.
"""
# ejemplo l = (1, 2, 10, 12]
for i in range(len(l)):
if l[i] == target:
return i
return -1
# Busqueda binaria:
def busqueda_binaria(l, target, low=None, high=None):
"""
Compara el valor con el elemento en el medio del array, si no son iguales,
la mitad en la cual el valor no puede estar es eliminada y la búsqueda
continúa en la mitad restante hasta que el valor se encuentre.
Este caso usa una lista ordenada.
"""
if low is None:
low = 0
if high is None:
high = len(l) - 1
if high < low:
return -1
# ejemplo l = (1, 3, 5, 10, 12] # debe retornar 3
midpoint = (low + high) // 2
if l[midpoint] == target:
return midpoint
elif target < l[midpoint]:
return busqueda_binaria(l, target, low, midpoint - 1)
else:
# target > l[midpoint]
return busqueda_binaria(l, target, midpoint + 1, high)
if __name__ == '__main__':
# l = [1, 3, 5, 10, 12]
# target = 10
# print(busqueda_simple(l, target))
# print(busqueda_binaria(l, target))
length = 1000
# Creación de lista ordenada de largo 1000
sorted_list = set()
while len(sorted_list) < length:
sorted_list.add(random.randint(-3 * length, 3 * length))
sorted_list = sorted(list(sorted_list))
#start = time.time()
#for target in sorted_list:
# busqueda_simple(sorted_list, target)
#end = time.time()
#total = round(((end - start)/length)*1000, 3)
#print("Busqueda Simple: ", total, "milisegundos")
start = time.time()
for target in sorted_list:
busqueda_binaria(sorted_list, target)
end = time.time()
total = round(((end - start)/length)*1000, 3)
print("Busqueda Binaria: ", total, "milisegundos")