How does a binary search algorithm work?

i want Explanation of binary search, how it divides the data in half to find an element in a sorted array.

1 Answer

The binary search algorithm works by repeatedly dividing the search range in half.The binary search algorithm is a fast method to find a target value in a sorted list or array. There are various step to calculate binary search algorithm some of them are mention below :

  • Steps of Binary Search: Start with a sorted array.
  • Set two pointers: low at the start and high at the end of the array.
  • Find the middle element: mid = (low + high) / 2
  • Compare the middle element with the target: If it's a match, return the index. If the target is less than the middle, search the left half.If the target is greater than the middle, search the right half. Repeat steps 3–4 until the target is found or the range becomes empty.
  • Example: Find 5 in the sorted array: [1, 3, 5, 7, 9] low = 0, high = 4 → mid = 2 → arr[2] = 5
  • Target matches arr[2], so return index 2

We use cookies to enhance your experience, to provide social media features and to analyse our traffic. By continuing to browse, you agree to our Privacy Policy.