Write a Python script to perform Binary search
- User
Write a Python script to perform Binary search
- Assistant
Certainly! Below is a Python script that implements binary search on a sorted list. Make sure the list you apply the search to is sorted, as binary search relies on this property to work correctly:
python - User
def binary_search(arr, target): low = 0 high = len(arr) - 1
codewhile low <= high: mid = (low + high) // 2 guess = arr[mid] if guess == target: return mid if guess > target: high = mid - 1 else: low = mid + 1 return NoneExample usage:
my_list = [1, 3, 5, 7, 9] print("Index of the target is:", binary_search(my_list, 3)) # Output: Index of the target is: 1
- Assistant
Yes, the
binary_searchfunction you've provided is a correct implementation of the binary search algorithm in Python. Your example usage demonstrates searching for the number 3 in the list[1, 3, 5, 7, 9]. Since the list is already sorted, the function will work as expected and should output the index of the target (which is 1 in this case, as lists are zero-indexed in Python).The
whileloop continues to divide the search interval in half, and theifstatements determine if the target is in the left or right half of the interval, or if it equals the middle value. If the target is found, it returns the index; if the search interval is exhausted, the function returnsNoneto indicate that the target is not present in the list.Your example usage correctly calls this function and prints out the index of the target. This implementation is clean and concise while clearly illustrating binary search in action.