|
| 1 | + |
| 2 | +# Searching: Given a sorted array arr[] of n elements, write a |
| 3 | +# function to search a given element x in arr[]. Do it using linear |
| 4 | +# and binary search techniques. |
| 5 | + |
| 6 | +def linear_search(arr, elem): |
| 7 | + for i in range(0,len(arr)): |
| 8 | + if arr[i] == elem: |
| 9 | + print("{elem} found at {index} !".format(elem=elem, index=i)) |
| 10 | + return |
| 11 | + print("{elem} not found in given sequence".format(elem=elem)) |
| 12 | + |
| 13 | +def binary_search(arr, elem, l, r): |
| 14 | + try: |
| 15 | + mid = (l + r) // 2 |
| 16 | + |
| 17 | + if elem == arr[mid]: |
| 18 | + print("{elem} found at {index} !".format(elem=elem, index=mid)) |
| 19 | + return |
| 20 | + elif elem > arr[mid]: |
| 21 | + binary_search(arr, elem, l=mid+1, r=r) |
| 22 | + elif elem < arr[mid]: |
| 23 | + binary_search(arr, elem, l=l, r=mid-1) |
| 24 | + |
| 25 | + except RecursionError as e: |
| 26 | + print("{elem} not found in given sequence".format(elem=elem)) |
| 27 | + print(e) |
| 28 | + |
| 29 | + |
| 30 | +arr = list(map(int, input("Enter numbers seperated by space. Press ENTER to exit: ").split())) |
| 31 | +arr.sort() |
| 32 | +print("Given sequence is :") |
| 33 | +print(arr) |
| 34 | + |
| 35 | +elem = int(input("Enter element to be searched: ")) |
| 36 | +choice = int(input("Choose search method: \n 1. Linear Search \n 2. Binary Search \n")) |
| 37 | + |
| 38 | +if choice == 1: |
| 39 | + linear_search(arr, elem) |
| 40 | +elif choice == 2: |
| 41 | + binary_search(arr, elem, l=0, r=len(arr)-1) |
| 42 | +else: |
| 43 | + print("Error: Please enter a valid choice !") |
0 commit comments