Share This Tutorial

Views 16

How Binary Search Algorithms Work

Author Zak  |  Date 2024-10-15 17:35:39  |  Category Computer Science
Back Back

How Binary Search Algorithms Work

Binary search is a highly efficient algorithm for finding a specific value within a sorted list or array. It works by repeatedly dividing the search interval in half. Here's how it functions:

  1. Initialization:
  2. Start with the entire sorted list as the search interval.
  3. Identify the middle element within this interval.

  4. Comparison:

  5. Compare the target value with the middle element:

    • If the target value matches the middle element, you've found it!
    • If the target value is less than the middle element, the search interval is narrowed to the left half.
    • If the target value is greater than the middle element, the search interval is narrowed to the right half.
  6. Iteration:

  7. Repeat steps 1 and 2 with the new search interval.
  8. Continue dividing the interval in half and comparing until the target value is found or the interval becomes empty.

  9. Result:

  10. If the target value is found, the algorithm returns its index (position).
  11. If the target value is not found, the algorithm returns an indication of its absence (e.g., -1).

Illustrative Example:

Let's find the number 35 in the sorted list: [5, 12, 20, 35, 48, 60, 72].

  1. Initialization:
  2. Search interval: [5, 12, 20, 35, 48, 60, 72]
  3. Middle element: 35

  4. Comparison:

  5. 35 (target) is equal to 35 (middle element), so the target value is found!

  6. Result:

  7. The algorithm returns the index of 35, which is 3.

Code Snippet (Conceptual):

function binarySearch(list, target):
  low = 0
  high = length(list) - 1
  while low <= high:
    mid = (low + high) // 2
    if list[mid] == target:
      return mid
    elif list[mid] < target:
      low = mid + 1
    else:
      high = mid - 1
  return -1

Advantages of Binary Search:

Limitations:

Applications: