Share This Tutorial

Views 18

Understanding Binary Search Algorithms

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

Understanding Binary Search Algorithms

Introduction

Binary search is a highly efficient algorithm used to search for a specific element within a sorted array. Its effectiveness stems from its divide-and-conquer strategy, repeatedly halving the search space until the target element is found or determined to be absent.

The Algorithm

  1. Initialization: Start with a sorted array and a target element you wish to find. Initialize two pointers, left and right, to the beginning and end of the array respectively.

  2. Iteration: While left is less than or equal to right:

  3. Calculate the middle index mid as the average of left and right.
  4. Compare the element at mid with the target element.

    • If they are equal, the search is successful.
    • If the target element is less than the element at mid, update right to mid - 1.
    • If the target element is greater than the element at mid, update left to mid + 1.
  5. Termination: If the loop terminates without finding the target element, it means the target element is not present in the array.

Implementation

function binarySearch(array, target) {
  let left = 0;
  let right = array.length - 1;

  while (left <= right) {
    let mid = Math.floor((left + right) / 2);

    if (array[mid] === target) {
      return mid; // Element found
    } else if (array[mid] < target) {
      left = mid + 1;
    } else {
      right = mid - 1;
    }
  }

  return -1; // Element not found
}

Example

Consider the following sorted array: [2, 5, 7, 8, 11, 12]. Let's search for the target element 11.

Time Complexity

Binary search has a time complexity of O(log n), where n is the number of elements in the array. This logarithmic complexity arises from the halving of the search space with each iteration.

Advantages

Disadvantages

Applications

Binary search finds widespread use in various applications: