Could you write a code describing binary search in python?
- User
Could you write a code describing binary search in python?
- Assistant
Certainly! Here's an example 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 -1 # Element not foundThis function takes an array
arr, an elementxto search for, and optionallowandhighindices to search within. It uses a binary search algorithm to find the index of the elementxin the array, or-1if the element is not found.
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.