Binary Search

Binary Search Algorithm

Binary Search is a search algorithm that finds the position of a target value within a sorted array. It efficiently locates the target value by repeatedly dividing the search interval in half. It is a highly efficient algorithm compared to linear search, especially for large datasets.

How Binary Search Works

  1. Array Partitioning:

    • Compare the target value with the middle element of the array.
    • If the target value matches the middle element, the position is returned.
    • If the target value is less than the middle element, search the left half of the array.
    • If the target value is greater, search the right half of the array.
  2. Repeated Search:

    • Repeat the process in the selected half of the array until the target value is found or the array becomes empty.
  3. Completion:

    • The search is complete when the target value is found or when the entire array is searched.

Key Features

  • Efficient Searching: Binary Search provides efficient search capabilities, especially on large, sorted datasets.

  • Divide and Conquer: It uses a divide-and-conquer strategy to quickly find the target value.

Efficiency

  • Time Complexity: Binary Search has a time complexity of O(log n), where n is the number of elements in the array.

  • Space Complexity: The space complexity is O(1) as it uses a constant amount of extra space.

Applications

  • Searching in Databases: It is commonly used in computer science and information systems for searching through sorted databases.

  • Efficient Searching: Binary Search is valuable in applications like searching in libraries, search engines, and array-based data structures.

Advantages

  • Efficiency: It is much more efficient than linear search, especially for large datasets.
  • Applicability: Binary Search works on sorted arrays and is simple to implement.

Disadvantages

  • Sorted Data Requirement: The input array must be sorted, which can be a limitation in certain scenarios.
  • Limited Applicability: It might not be suitable for unsorted or constantly changing datasets.

Binary Search Algorithm Implementation in JavaScript

Here's an example of Binary Search implemented in JavaScript:

Sorting-Algo/bns.js
function binarySearch(arr, target) {
    let left = 0;
    let right = arr.length - 1;
 
    while (left <= right) {
        const mid = Math.floor((left + right) / 2);
 
        if (arr[mid] === target) {
            return mid;
        } else if (arr[mid] < target) {
            left = mid + 1;
        } else {
            right = mid - 1;
        }
    }
 
    return -1;
}
 
// Example usage
const sortedArray = [2, 3, 5, 8, 12, 18, 21, 30, 37];
const targetValue = 12;
const position = binarySearch(sortedArray, targetValue);
console.log("Target value found at position:", position);