How do you perform …
 
Notifications
Clear all

How do you perform a binary search in a given array?

1 Posts
2 Users
2 Likes
278 Views
1
Topic starter

Binary Search - GeeksforGeeks

1 Answer
1

here is a step-by-step guide on how to perform a binary search in a given array:

  1. Sort the array in ascending or descending order.
  2. Set two pointers: left pointer (l) at the beginning of the array and right pointer (r) at the end of the array.
  3. Compute the middle index of the array by taking the average of left and right pointers: mid = (l + r) / 2
  4. If the target value is equal to the value at the middle index, return the middle index.
  5. If the target value is less than the value at the middle index, set the right pointer to mid – 1 and go to step 3.
  6. If the target value is greater than the value at the middle index, set the left pointer to mid + 1 and go to step 3.
  7. Repeat steps 3 to 6 until the target value is found or the left pointer is greater than the right pointer.
  8. If the target value is not found, return -1 to indicate that the value is not in the array.

This algorithm has a time complexity of O(log n) because it cuts the search space in half on each iteration, making it very efficient for searching large sorted arrays.

Share: