I have completed an iterative implementation of Binary Search in python and was wondering if there is an efficient way to ensure that your input is always sorted before sorting it if needed. How can one validate the input to be sorted? What is the time complexity if the input is not sorted? I would also appreciate comments if this code can be made more efficient.
def binary_search(array, search):
low = 0
high = len(array)
while low <= high and len(array[low:high]):
mid = (low + high) // 2
if array[mid] == search:
return "Found " + str(search) + " at index " + str(mid)
elif search > array[mid]:
low = mid + 1
elif search < array[mid]:
high = mid - 1
return str(search) + " not found."
search_through = [2, 3, 4, 10, 40]
to_search = 49
print(binary_search(search_through, to_search))
Output: 49 not found.