Sep-02-2017, 11:01 AM
what hbknjr says is correct:
If you add one more statement to for routine and slight modification to print statements, the error becomes clear:
inputs:
C:\Python36\python.exe M:/python/ProvingGround/newStuff/FindIndex1.py
Enter list of element:2,3,4,5,6
Enter search element:5
If you add one more statement to for routine and slight modification to print statements, the error becomes clear:
def binarySearch(arr, first, last, element): print('value of arr: {}'.format(arr)) mid = first + last // 2 print("Value of mid: {}".format(mid)) print("Value of arr[mid]: {}".format(arr[mid])) if last >= first: if (element == arr[mid]): print("element", element, "found at location ", mid) else: if (element > arr[mid]): return binarySearch(arr, mid + 1, last, element) else: return binarySearch(arr, first, mid - 1, element) else: print("Element is not present in array") arr = [int(x) for x in input("Enter list of element:").split(',')] element = int(input("Enter search element:")) binarySearch(arr, 0, len(arr) - 1, element)first crash from your attempts:
inputs:
Output:Enter list of element:2,3,4,5,6
Enter search element:5
results:C:\Python36\python.exe M:/python/ProvingGround/newStuff/FindIndex1.py
Enter list of element:2,3,4,5,6
Enter search element:5
Output:Traceback (most recent call last):
File "M:/python/ProvingGround/newStuff/FindIndex1.py", line 20, in <module>
binarySearch(arr, 0, len(arr) - 1, element)
File "M:/python/ProvingGround/newStuff/FindIndex1.py", line 11, in binarySearch
return binarySearch(arr, mid + 1, last, element)
File "M:/python/ProvingGround/newStuff/FindIndex1.py", line 5, in binarySearch
print("Value of arr[mid]: {}".format(arr[mid]))
IndexError: list index out of range
value of arr: [2, 3, 4, 5, 6]
Value of mid: 2
Value of arr[mid]: 4
value of arr: [2, 3, 4, 5, 6]
Value of mid: 5
You can see here that there is no element 5 ... remember index is 0 to 4