Write a program in Python that performs binary search
- User
Write a program in Python that performs binary search
- Assistant
Here's an implementation of binary search in Python:
def binary_search(arr, x): low = 0 high = len(arr) - 1 while low <= high: mid = (low + high) // 2 if arr[mid] == x: return mid elif arr[mid] < x: low = mid + 1 else: high = mid - 1 return -1This function takes an array
arrand a valuexto search for. It starts by settinglowto 0 andhighto the last index ofarr. It then enters a loop that continues as long aslowis less than or equal tohigh. On each iteration, the function calculates the middle indexmid, and compares the value atarr[mid]to the target valuex. If they match, the function returnsmid. Ifarr[mid]is less thanx, it restricts the search to the upper half of the array by settinglowtomid + 1. Ifarr[mid]is greater thanx, it restricts the search to the lower half of the array by settinghightomid - 1. If the search completes without finding the target value, the function returns -1.
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.