1def binary_search(a, key):
2 low = 0
3 high = len(a) - 1
4 while low < high:
5 mid = (low + high) // 2
6 if key == a[mid]:
7 return True
8 elif key < mid:
9 high = mid - 1
10 else:
11 low = mid + 1
12
13 return False
1# This is real binary search
2# this algorithm works very good because it is recursive
3
4def binarySearch(arr, min, max, x):
5 if max >= min:
6 i = int(min + (max - min) / 2) # average
7 if arr[i] == x:
8 return i
9 elif arr[i] < x:
10 return binarySearch(arr, i + 1, max, x)
11 else:
12 return binarySearch(arr, min, i - 1, x)
13
1#binary search python
2def binaryy(ar, ele):
3 low = 0
4 high = len(ar)-1
5 if ele not in ar:
6 return "Not Found"
7 while low <= high:
8 mid = (low + high) // 2
9 if ar[mid] < ele:
10 low = mid + 1
11 elif ar[mid] > ele:
12 high = mid - 1
13 else:
14 return mid
15
16
17ar = [10, 20, 30, 40, 50]
18ele = 55
19print(binaryy(ar, ele))
1#grepper
2
3def binary_search(item_list,item):
4 first = 0
5 last = len(item_list)-1
6 found = False
7 while( first<=last and not found):
8 mid = (first + last)//2
9 if item_list[mid] == item :
10 found = True
11 else:
12 if item < item_list[mid]:
13 last = mid - 1
14 else:
15 first = mid + 1
16 return found
1def binary_search_recursive(list_of_numbers, number, start=0, end=None):
2
3 # The end of our search is initialized to None. First we set the end to the length of the sequence.
4 if end is None:
5 end = len(list_of_numbers) - 1
6
7 if start > end:
8 # This will happen if the list is empty of the number is not found in the list.
9 raise ValueError('Number not in list')
10
11 mid = (start + end) // 2 # This is the mid value of our binary search.
12
13 if number == list_of_numbers[mid]:
14 # We have found the number in our list. Let's return the index.
15 return mid
16
17 if number < list_of_numbers[mid]:
18 # Number lies in the lower half. So we call the function again changing the end value to 'mid - 1' Here we are entering the recursive mode.
19
20
21
22 return binary_search_recursive(list_of_numbers, number, start, mid - 1)
23 # number > list_of_numbers[mid]
24 # Number lies in the upper half. So we call the function again changing the start value to 'mid + 1' Here we are entering the recursive mode.
25
26 return binary_search_recursive(list_of_numbers, number, mid + 1, end)
27
1def binary_search(group, suspect):
2 group.sort()
3 midpoint = len(group)//2
4 while(True):
5 if(group[midpoint] == suspect):
6 return midpoint
7 if(suspect > group[midpoint]):
8 group = group[midpoint]
9 if(suspect < group[midpoint]):
10 group = group[0: midpoint]
11 midpoint = (len(group)//2)