In Python, which of the following is a correct implementation of binary search?

Practice Questions

Q1
In Python, which of the following is a correct implementation of binary search?
  1. def binary_search(arr, x): ...
  2. def binary_search(arr, x): return arr.index(x)
  3. def binary_search(arr, x): for i in arr: if i == x: return i
  4. def binary_search(arr, x): while arr: ...

Questions & Step-by-Step Solutions

In Python, which of the following is a correct implementation of binary search?
  • 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.
No concepts available.
Soulshift Feedback ×

On a scale of 0–10, how likely are you to recommend The Soulshift Academy?

Not likely Very likely