input | output |
---|---|
n : size of array arr[] : sorted array of n elements x : target element |
i : index of target element |
input:
7
1 2 4 5 6 7 9
6
output:
4
-
find the
middle
element -
if
middle
element is larger thantarget
element then look in left subtree -
if
middle
element is smaller thetarget
element then look in right subtree -
if
middle
element is equal totarget
element then return theindex
-
if
target
element is not found then return-1
def binarySearch(arr, size, target):
l, r = 0, size-1
while l <= r:
m = l + (r - l) // 2
if arr[m] == target:
return m
elif arr[m] > target:
r = m - 1
else:
l = m + 1
return -1
n = int(input())
arr = list(map(int, input().split()))
index = binarySearch(arr, n, int(input()))
print(index)
T(n) = T(n / 2) + 1 , if n > 1
T(n) = 1 , if n = 1
T(n) = O(log(n))
S(n) = O(1)