Algorithm


Binary Search Algorithm:

  1. Start with a sorted array and a target element to search for.
  2. Initialize two pointers, one at the beginning of the array and one at the end.
  3. Repeat the following steps until the pointers meet:
    1. Find the middle element of the current array segment.
    2. Compare the middle element with the target element.
    3. If they match, return the index of the middle element.
    4. If the target element is smaller than the middle element, move the end pointer to the middle - 1.
    5. If the target element is larger than the middle element, move the start pointer to the middle + 1.
  4. If the pointers meet without finding the target element, return "Not Found."

Example:

Binary Search Example

Fig. 1: Step-by-Step Process of Binary Search

Note: Binary Search is efficient but requires the input array to be sorted.