Question: I have two sets of Python code that find an element in an array and returns which index that element is at. One is a
I have two sets of Python code that find an element in an array and returns which index that element is at. One is a binary search and the other is a linear search. I would also like to add some code to count the amount of iterations that each one does. Thank you!
Binary:
def binary_search(array, x, low, high): if high >= low: mid = low + (high - low)//2 if array [mid] == x: return mid elif array[mid] > x: return binary_search(array, x, low, mid-1) else: return binary_search(array, x, mid + 1, high) else: return -1 array = [2, 3, 6, 9, 12, 15, 19] x = 12
result = binary_search(array, x, 0, len(array)-1)
if result != -1: print("Element is present at index " + str(result)) else: print("Not found")
Linear:
def linearSearch(array, n, x): for i in range(0, n): if (array[i] == x): return i return -1 array = [2, 3, 6, 9, 12, 15, 19] x = 12 n = len(array) result = linearSearch(array, n, x) if(result == -1): print("Element not found.") else: print("Element found at index: ", result)
Step by Step Solution
There are 3 Steps involved in it
Get step-by-step solutions from verified subject matter experts
