This is Qiita's first post.
This time, I implemented binary search in two patterns, loop and recursion.
binary_search_loop.py
from typing import List
def binary_search_loop(data: List[int], target: int) -> int:
left, right = 0, len(data)
while left <= right:
mid = (left + right) // 2
if data[mid] == target:
return mid
elif data[mid] < target:
left = mid + 1
else:
right = mid - 1
return None
if __name__ == "__main__":
data: List[int] = [int(x) for x in input("Sorted array(Space delimited)Enter: ").split()] #I used the inclusion notation
target = int(input("Enter target: "))
result = binary_search_loop(data, target)
if result is not None:
print(f"found: {result}Was second")
else:
print("not found")
binary_search_recursion.py
from typing import List
def binary_search_recursion(data: List[int], target: int) -> int:
def recursion(left=0, right=len(data) - 1):
if left > right:
return None
mid = (left + right) // 2
if data[mid] == target:
return mid
elif data[mid] < target:
return recursion(mid + 1, right)
else:
return recursion(left, mid - 1)
return recursion()
if __name__ == "__main__":
data: List[int] = list(map(int, input("Sorted array(Space delimited)Enter: ").split())) #Using map
target = int(input("Enter target: "))
result = binary_search_recursion(data, target)
if result is not None:
print(f"found: {result}Was second")
else:
print("not found")
--Since the data obtained by input () is str type, convert it to int type. --If it is still str type, it will be compared by character code instead of number in comparison.
Recommended Posts