In Python, which of the following is a correct implementation of binary search?
Practice Questions
1 question
Q1
In Python, which of the following is a correct implementation of binary search?
def binary_search(arr, x): ...
def binary_search(arr, x): return arr.index(x)
def binary_search(arr, x): for i in arr: if i == x: return i
def binary_search(arr, x): while arr: ...
The correct implementation of binary search involves a function that takes an array and a target value, and uses a loop to narrow down the search.
Questions & Step-by-step Solutions
1 item
Q
Q: In Python, which of the following is a correct implementation of binary search?
Solution: The correct implementation of binary search involves a function that takes an array and a target value, and uses a loop to narrow down the search.
Steps: 8
Step 1: Define a function that takes two parameters: an array (list of numbers) and a target value (the number you want to find).
Step 2: Initialize two variables, 'left' and 'right', to represent the start and end indices of the array.
Step 3: Use a loop that continues as long as 'left' is less than or equal to 'right'.
Step 4: Inside the loop, calculate the middle index by taking the average of 'left' and 'right'.
Step 5: Check if the middle element of the array is equal to the target value. If it is, return the middle index.
Step 6: If the middle element is less than the target value, move the 'left' index to 'middle + 1' to search the right half of the array.
Step 7: If the middle element is greater than the target value, move the 'right' index to 'middle - 1' to search the left half of the array.
Step 8: If the loop ends and the target value is not found, return -1 or a message indicating that the target is not in the array.