Given a sorted list of numbers, I need to find the smallest number that is greater than a given number. Consider this list:
JavaScript
x
2
1
arr=[1,2,3,5,7,11,101,131,151,181,191,313,353,373,383]
2
Say the specified number is 320. Then, my method should return 353 as 353 is the smallest number greater than 320.
I am trying to use a slightly modified form of binary search; however on execution the program goes into infinite loop.
JavaScript
1
14
14
1
def modBinarySearch(arr,x):
2
l=len(arr)
3
mid=l/2
4
if arr[mid]>=x and arr[mid-1]<x:
5
return arr[mid]
6
elif arr[mid]>x and arr[mid-1]>x:
7
modBinarySearch(arr[mid:l],x)
8
else:
9
modBinarySearch(arr[0:mid],x)
10
11
N=int(raw_input())
12
arr=[1,2,3,5,7,11,101,131,151,181,191,313,353,373,383]
13
print modBinarySearch(arr,N)
14
Can someone point out what I am doing wrong ?
Advertisement
Answer
If arr[mid] and arr[mid-1], both are greater than your number, you should search in arr[0:mid], don’t you think?
JavaScript
1
5
1
elif arr[mid]>x and arr[mid-1]>x:
2
modBinarySearch(arr[0:mid],x)
3
else:
4
modBinarySearch(arr[mid:1],x)
5