def test(self): test_a = [1, 3, 4, 6, 7] get_result = binary_search(test_a, key=6) self.assertEqual(get_result[0], True, msg="Searching Fail") self.assertEqual(get_result[1], 3, msg="Invalid index") test_b = [10, 20, 30, 40, 50] get_result = binary_search(test_b, key=6) self.assertEqual(get_result[0], False, msg="Searching Fail") self.assertEqual(get_result[1], None, msg="Invalid index")
def val_in_list(input_list, input_val): val_index = binary_search(input_list, input_val) if(val_index != -1): print str(input_val) + " found at index " + str(val_index) + "!" return True else: print str(input_val) + " not found in input list" return False
def exponential_search(arr: [int], key: int) -> int: """ Performs exponential search over given array. Performs great in unbounded array and when element to be searched is closer to starting index. Time complexity : O(log(n)) :param arr: Sorted input array. :param key: Value to be found out. :return: Index of key if it is present in the array else -1. """ # Calculate the length of array. n = len(arr) # Check if first element matches the key. if arr[0] == key: return 0 # Find index i where arr[i] > key. i = 1 while i < n and arr[i] <= key: i = i * 2 # Perform binary search over the target array. return binary_search(arr, key, int(i / 2), min(i, n - 1))
def test1(self): arr = [1, 2, 3, 4, 5, 6, 7] val = 4 assert binary_search(arr, val) == True
def test4(self): arr = [1, 2, 3, 4, 5, 6, 7] val = 9 assert binary_search(arr, val) == False
def test_binary_search(self): foo = [1,32,56,84,97,105,325,725] self.assertEqual(binary_search(foo, 32), True)