binary search js

By : cs

Language: javascript

Date Published: 2 weeks, 4 days ago

Binary Search is an efficient algorithm to find an element in a sorted array.
It works by repeatedly dividing the search interval in half:

Compare the target value to the middle element.

If they are equal — the search is successful.

If the target is smaller — continue searching in the left half.

If the target is larger — continue searching in the right half.

Time Complexity: O(log n)
Requirement: The array must be sorted.

Style : Dark Mode : Line Number: Download Font Size:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
// Binary Search Implementation in JavaScript

/**
 * Performs binary search on a sorted array
 * @param {number[]} arr - Sorted array to search in
 * @param {number} target - Element to find
 * @returns {number} Index of target if found, else -1
 */
function binarySearch(arr, target) {
  let left = 0;
  let right = arr.length - 1;

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

    // Check if middle element is the target
    if (arr[mid] === target) {
      return mid; // Found the target
    }
    // If target is smaller, ignore right half
    else if (arr[mid] > target) {
      right = mid - 1;
    }
    // If target is larger, ignore left half
    else {
      left = mid + 1;
    }
  }

  // If not found
  return -1;
}

// Example usage:
const numbers = [2, 5, 8, 12, 16, 23, 38, 56, 72, 91];
const target = 23;

const result = binarySearch(numbers, target);

// Display result
if (result !== -1) {
  console.log(`Element ${target} found at index ${result}`);
} else {
  console.log(`Element ${target} not found in the array`);
}
algorithm, search, recursion, data-structures
Login to see the comments