- Notifications
You must be signed in to change notification settings - Fork 366
/
Copy pathfindClosestNumberr.py
37 lines (33 loc) · 963 Bytes
/
findClosestNumberr.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
defget_closest(val1, val2, t):
ifabs(val1-t) <=abs(val2-t):
returnval1
else:
returnval2
deffind_closest(arr, n, t):
"""
Using Binary Search find the number closest
to target in the given sorted array
"""
ift<=arr[0]:
returnarr[0]
elift>=arr[n-1]:
returnarr[n-1]
left, right=0, n
whileleft<right:
mid= (left+right) //2
ifarr[mid] ==t:
returnarr[mid]
elift<arr[mid]:
ifmid>0andarr[mid-1] <t:
returnget_closest(arr[mid-1], arr[mid], t)
right=mid
else:
ifmid<n-1andarr[mid+1] >t:
returnget_closest(arr[mid], arr[mid+1], t)
left=mid+1
returnarr[mid]
if__name__=="__main__":
array= [1, 2, 4, 5, 6, 6, 8, 9]
size=len(array)
target=7
print(find_closest(array, size, target))