upd binary searches

This commit is contained in:
onyx-and-iris 2024-01-08 10:38:49 +00:00
parent d646cb83c1
commit ea9af3f1c7
2 changed files with 53 additions and 14 deletions

View File

@ -6,13 +6,7 @@ logging.basicConfig(level=logging.DEBUG)
logger = logging.getLogger(__name__) logger = logging.getLogger(__name__)
LOWER = 1000
UPPER = 1000000
SAMPLE_SIZE = 1000
def binary_search(arr, item): def binary_search(arr, item):
count = 1
low = 0 low = 0
high = len(arr) - 1 high = len(arr) - 1
@ -20,27 +14,29 @@ def binary_search(arr, item):
mid = (low + high) // 2 mid = (low + high) // 2
guess = arr[mid] guess = arr[mid]
if guess == item: if guess == item:
logger.debug(f"found item after {count} splits")
return mid return mid
elif guess > item: elif guess > item:
high = mid - 1 high = mid - 1
else: else:
low = mid + 1 low = mid + 1
count += 1
return None return None
LOWER = 1000
UPPER = 1000000
SAMPLE_SIZE = 1000
numbers = random.sample(range(LOWER, UPPER), SAMPLE_SIZE) numbers = random.sample(range(LOWER, UPPER), SAMPLE_SIZE)
numbers.sort() numbers.sort()
logger.debug(numbers)
start = time.time() start = time.time()
res = None result = None
while res is None: while result is None:
guess = random.randrange(LOWER, UPPER) guess = random.randrange(LOWER, UPPER)
res = binary_search(numbers, guess) logger.debug(f"guess: {guess}")
result = binary_search(numbers, guess)
print(f"Found {guess} at index {res}. Running time {time.time() - start}") print(f"Found {guess} at index {result}. Running time {time.time() - start}")

43
chapter4/binary.py Normal file
View File

@ -0,0 +1,43 @@
import logging
import random
import time
logging.basicConfig(level=logging.DEBUG)
logger = logging.getLogger(__name__)
def binary_search(arr, low, high, x):
# x not found, low has overlapped high so we return None
if high < low:
return
mid = (high + low) // 2
# x found at middle of split, return its index
if arr[mid] == x:
return mid
# x in left side of split
elif arr[mid] > x:
return binary_search(arr, low, mid - 1, x)
# x in right side of split
else:
return binary_search(arr, mid + 1, high, x)
LOWER = 1000
UPPER = 1000000
SAMPLE_SIZE = 1000
numbers = random.sample(range(LOWER, UPPER), SAMPLE_SIZE)
numbers.sort()
start = time.time()
result = None
while result is None:
guess = random.randrange(LOWER, UPPER)
logger.debug(f"guess: {guess}")
result = binary_search(numbers, 0, len(numbers) - 1, guess)
print(f"Found {guess} at index {result}. Running time {time.time() - start}")