code in python using binary search
- User
code in python using binary search
Assistant
Here is a Python implementation of binary search:
pythondef binary_search(list, target): first = 0 last = len(list) - 1 while first <= last: mid = (first + last) // 2 if list[mid] == target: return mid elif list[mid] < target: first = mid + 1 else: last = mid - 1 return -1 list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] target = 6 index = binary_search(list, target) print(index) # 5This performs a binary search on the list. It keeps track of the first and last indices of the search space. In each iteration, it calculates the middle index and checks if the element at matches the target. If so, it returns the mid index. If not, it halves the search space by updating either or and continues searching. If the entire list is searched and the target is not found, is returned.
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.