Binary Search Python:
Finding target number in a sorted List
def binary_search(arr, target):
left = 0
right = len(arr) - 1
while left <= right:
mid = left + (right - left) // 2
if arr[mid] == target:
return mid
elif target < arr[mid]:
right = mid - 1
else:
left = mid + 1
return -1
arr = [1, 2, 3, 4, 5, 6, 7, 8, 9]
target = 5
print(binary_search(arr, target)) # Output: 4
Explanation:
left = 0
right = len(nums) - 1
# Loop until the bounds converge
while left <= right:
# Find the midpoint of the current search bounds
mid = left + (right - left) // 2
# Check if the midpoint is the target
if nums[mid] == target:
return mid
# If the target is less than the midpoint, search the left half
elif target < nums[mid]:
right = mid - 1
# If the target is greater than the midpoint, search the right half
else:
left = mid + 1
# Return -1 if the target is not found
return -1
'알고리즘 문제 > CP코드 저장소' 카테고리의 다른 글
List 값들의 정렬 (2차원 배열 / 길이) (0) | 2022.12.31 |
---|---|
RoundUp (0) | 2022.12.30 |
정렬 : 리스트의 x번째 원소 (0) | 2022.12.02 |
Lcm, Gcd (0) | 2022.12.01 |
소수(Prime Number) 찾기 (0) | 2022.12.01 |