Example:2
Write a python script to search an element with in a list using Binary Search.(Create a user defined list)
Sol:
def binary_search(arr, x): low = 0 high = len(arr) - 1 mid = 0 while low <= high: mid = (high + low) // 2 # Check if x is present at mid if arr[mid] < x: low = mid + 1 # If x is greater, ignore left half elif arr[mid] > x: high = mid - 1 # If x is smaller, ignore right half else: return mid # If we reach here, then the element was not present return -1 #-- main -- # create a user defined list arr=[] while True: a=int(input("Enter the element to add ")) arr.append(a) ch=input("Like to cont (y/n) ") if(ch=="y" or ch=="Y"): continue; else: break #to display the list print(arr) #to sort the elements of the list arr arr.sort() #condition for binary search is elements should be sorted print("Sorted list") print(arr) x=int(input("Enter the element to search ")) # Function call result = binary_search(arr, x) if result != -1: print("Element is present at index", str(result)," position = ",str(result+1)) else: print("Element is not present in array")
Output:
Enter the element to add 10 Like to cont (y/n) y Enter the element to add 25 Like to cont (y/n) y Enter the element to add 96 Like to cont (y/n) y Enter the element to add 4 Like to cont (y/n) y Enter the element to add 65 Like to cont (y/n) n [10, 25, 96, 4, 65] Sorted list [4, 10, 25, 65, 96] Enter the element to search 25 Element is present at index 2 position = 3