Looks like you're stuck. Need a hand?

Share This Tutorial

Views 119

How Binary Search Algorithms Work

Date  |  Category Computer Science
...
...
Learning Paths Learning Paths

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: - Start with the entire sorted list as the search interval. - Identify the middle element within this interval.

  2. Comparison: - 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.
  3. Iteration: - Repeat steps 1 and 2 with the new search interval. - Continue dividing the interval in half and comparing until the target value is found or the interval becomes empty.

  4. Result: - If the target value is found, the algorithm returns its index (position). - 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: - Search interval: [5, 12, 20, 35, 48, 60, 72] - Middle element: 35

  2. Comparison: - 35 (target) is equal to 35 (middle element), so the target value is found!

  3. Result: - 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: