Description: The Binary Search algorithm (also known as half-interval search) is used to find an element within a sorted array. The algorithm works by halving the search space at each step. First, it compares the middle element of the array with the target value. Depending on whether the target value is greater or smaller than the middle element, the search continues in the corresponding half (left or right). This process repeats until the element is found or the search range is reduced to zero.

Example Walkthrough

Suppose we have the following sorted array: [1, 3, 5, 7, 9, 11, 13, 15, 17]

We are searching for the number 7.

  1. Compare with the middle element of the array (in this case, 9):
  2. 7 is less than 9, so we narrow our search range to the left sub-array: [1, 3, 5, 7].
  3. Compare with the middle element of the left half (e.g., 3 or 5 depending on rounding):
  4. If middle is 7, 7 == 7, meaning the target element has been found.

Algorithm Steps

  1. Define the search range: from the start to the end of the array.
  2. Find the middle of this range.
  3. If the middle element is equal to the target value, terminate the search.
  4. If the target element is less than the middle element, repeat the search on the left half.
  5. If the target element is greater than the middle element, repeat the search on the right half.
  6. Repeat steps 2–5 until the element is found or the search range becomes empty.

Complexity

  • Time Complexity: O(log n), where n is the number of elements in the array. This means doubling the size of the array increases the required steps by only 1.
  • Space Complexity: O(1) — the iterative algorithm requires a constant amount of memory because it operates in place without allocating additional data structures.

Applications

  • Search in Sorted Collections: Binary search is used to locate elements in sorted arrays or lists, which is beneficial for databases and search engines.
  • Binary Search Trees (BST): The core principle of binary search is applied to locate nodes within balanced search trees.
  • Large Datasets: Binary search efficiently handles massive volumes of data when querying sorted datasets.

Advantages

  • Extremely efficient for searching in pre-sorted data.
  • Search time grows logarithmically, enabling fast processing of large volumes of information.

Disadvantages

  • Works strictly on sorted arrays or lists. If the data is unsorted, it must be sorted first, adding extra computational complexity (typically O(n log n)).