The idea of binary search is to use the information that the array is sorted and reduce the time complexity to O(Log n).
class BinarySearch(object) : def binarySearch(self, A, K): # Returns index of x in arr if present, else -1
def binarySearch(arr, l, r, x): # Check base case
if r >= l: print("r,l:",r,", ",l) mid = round(l + (r - l) / 2) # If element is present at the middle itself
if arr[mid] == x: return mid # If element is smaller than mid, then it can only
# be present in left subarray
elif arr[mid] == x: print("search left side of the array: arr[mid] is ", arr[mid]) return binarySearch(arr, l, mid - 1, x) # Else the element can only be present in right subarray
else: print("search right side of the array: arr[mid] is ", arr[mid]) return binarySearch(arr, mid + 1, r, x) else: # Element is not present in the array
return -1 result = binarySearch(A, 0, len(A)-1, K) return result def main(): x = BinarySearch() A = [10, 7, 8, 9, 1, 5] k = 1 #output = 8 #A =[7, 10, 4, 3, 20, 15] A.sort() print("array is: ",A) print("element ",k, " of array ", A, " is index ", x.binarySearch(A,k)) if __name__ == '__main__': main()
No comments:
Post a Comment