When it is required to implement binary search without using dictionary, a method can be defined that checks the first and last index of the list, and gets the middle value of the list.
It is then compared to the value that needs to be checked for. If it is found, the value is returned. Else, -1 is returned.
It is important to remember that binary search works on sorted elements only, either ascending or descending order.
A list can be used to store heterogeneous values (i.e data of any data type like integer, floating point, strings, and so on).
Below is a demonstration for the same −
def binary_search(my_list, elem): low = 0 high = len(my_list) - 1 mid = 0 while low <= high: mid = (high + low) // 2 if my_list[mid] < elem: low = mid + 1 elif my_list[mid] > elem: high = mid - 1 else: return mid return -1 my_list = [ 1, 9, 11, 21, 34, 54, 67, 90 ] elem_to_search = 1 print("The list is") print(my_list) my_result = binary_search(my_list, elem_to_search) if my_result != -1: print("Element found at index ", str(my_result)) else: print("Element not found!")
The list is [1, 9, 11, 21, 34, 54, 67, 90] Element found at index 0