Binary Search Algorithm

Binary search is a searching algorithm that finds the position of a target value within a sorted array or list. It is a divide-and-conquer algorithm that works by repeatedly dividing the search interval in half.

Binary search is efficient for searching in large datasets because it reduces the search space by half with each comparison. Its time complexity is O(log n), where n is the number of elements in the array.

Binary Search Algorithm Implementation in JavaScript:

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

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

    // Check if the middle element is the target
    if (arr[mid] === target) {
      return mid; // Target found, return its index
    } else if (arr[mid] < target) {
      // If target is greater, ignore the left half
      left = mid + 1;
    } else {
      // If target is smaller, ignore the right half
      right = mid - 1;
    }
  }

  return -1; // Target not found
}

// Example usage:
const sortedArray = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
const targetValue = 7;

const result = binarySearch(sortedArray, targetValue);

if (result !== -1) {
  console.log(`Element ${targetValue} found at index ${result}.`);
} else {
  console.log(`Element ${targetValue} not found in the array.`);
}

You need to be logged in to view the rest of the content. Please . Not a Member? Join Us

Leave a Comment

Pin It on Pinterest

Scroll to Top