grokking-algorithms/chapter1/binary.py

43 lines
813 B
Python
Raw Normal View History

2024-01-04 17:41:01 +00:00
import logging
import random
import time
logging.basicConfig(level=logging.DEBUG)
logger = logging.getLogger(__name__)
def binary_search(arr, item):
low = 0
high = len(arr) - 1
while low <= high:
mid = (low + high) // 2
guess = arr[mid]
if guess == item:
return mid
elif guess > item:
high = mid - 1
else:
low = mid + 1
return None
2024-01-08 10:38:49 +00:00
LOWER = 1000
UPPER = 1000000
SAMPLE_SIZE = 1000
2024-01-04 17:41:01 +00:00
numbers = random.sample(range(LOWER, UPPER), SAMPLE_SIZE)
numbers.sort()
start = time.time()
2024-01-08 10:38:49 +00:00
result = None
while result is None:
2024-01-04 17:41:01 +00:00
guess = random.randrange(LOWER, UPPER)
2024-01-08 10:38:49 +00:00
logger.debug(f"guess: {guess}")
result = binary_search(numbers, guess)
2024-01-04 17:41:01 +00:00
2024-01-08 10:38:49 +00:00
print(f"Found {guess} at index {result}. Running time {time.time() - start}")