mirror of
https://github.com/onyx-and-iris/grokking-algorithms.git
synced 2026-04-16 11:33:34 +00:00
reorganise directories
upd chapter_01/binary.py
This commit is contained in:
5
chapter_01/README.md
Normal file
5
chapter_01/README.md
Normal file
@@ -0,0 +1,5 @@
|
||||
# Binary Search
|
||||
|
||||
Repeatedly split the array checking if value is greater or less than the mid point. Stop when the exact value is found.
|
||||
|
||||
It takes log N steps to reduce an array of size N to an array of size 1. Time complexity for this algorithm is `O(log N)`.
|
||||
44
chapter_01/binary.py
Normal file
44
chapter_01/binary.py
Normal file
@@ -0,0 +1,44 @@
|
||||
import logging
|
||||
import random
|
||||
|
||||
logging.basicConfig(level=logging.DEBUG)
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
class BinarySearch:
|
||||
def __init__(self, arr):
|
||||
self._arr = arr
|
||||
|
||||
def search(self, item):
|
||||
low = 0
|
||||
high = len(self._arr) - 1
|
||||
|
||||
while low <= high:
|
||||
mid = (low + high) // 2
|
||||
guess = self._arr[mid]
|
||||
if guess == item:
|
||||
return mid
|
||||
elif guess > item:
|
||||
high = mid - 1
|
||||
else:
|
||||
low = mid + 1
|
||||
|
||||
return None
|
||||
|
||||
|
||||
LOWER = 1000
|
||||
UPPER = 1000000
|
||||
SAMPLE_SIZE = 1000
|
||||
|
||||
|
||||
numbers = random.sample(range(LOWER, UPPER), SAMPLE_SIZE)
|
||||
numbers.extend([9000, 999999])
|
||||
numbers.sort()
|
||||
print(numbers)
|
||||
|
||||
search = BinarySearch(numbers)
|
||||
print(search.search(42))
|
||||
print(search.search(9000))
|
||||
print(search.search(20000))
|
||||
print(search.search(60000))
|
||||
print(search.search(999999))
|
||||
Reference in New Issue
Block a user