DEV Community 👩‍💻👨‍💻

Aya Bouchiha
Aya Bouchiha

Posted on • Updated on

Binary search algorithm

Hi, this is #day_6, we're going to talk about Binary Search Algorithm.

Definition of the binary search algorithm

binary search also called half-interval search, or logarithmic search is one of the most famous search algorithms,

this algorithm search a sorted array by repeatedly dividing the search interval in half. Begin with an interval covering the whole array. If the value of the search key is less than the item in the middle of the interval, narrow the interval to the lower half. Otherwise, narrow it to the upper half. Repeatedly check until the value is found or the interval is empty.

Space and Time complexity

The space complexity of linear search is O(1) and his Time complexity is O(log n).

Implementation of binary search in python

def BinarySearchAlgorithm(wantedItem: int, sortedItems: list):
    =>  Algorithm Name : Binary Search
    =>  Algorithm Type : Searching Algorithms
    =>  Time Complexity : O(n)
    =>  Space Complexity : O(1)
    =>  Logic
        [ if wantedItem == mid ]
        [ if wantedItem < sortedItems[mid] ] eliminate right half
        [ if wantedItem > sortedItems[mid] ] eliminate left half
    =>  Arguments
        [sortedItems] {list<int>} sorted list
    => Returns
        [index] if the wanted item exists in the list
        [False] if the wanted item doesn't exist in the list
    low = 0
    high = len(sortedItems) - 1
    while low <= high :
        mid = (high + low) // 2
        if wantedItem == sortedItems[mid]:
            return mid
        elif wantedItem > sortedItems[mid]:
            # eliminate left half
            low = mid + 1
            # eliminate right half
            hight = mid - 1
    # if the item dosen't exist
    return False
Enter fullscreen mode Exit fullscreen mode

Implementation of binary search in javascript

 * binary search algorithm
 * Time Complexity: O(log n)
 * Space Complexity: O(1)
 * @param wantedItem {Number} the desired element
 * @param sortedItems {Array<Number>} sorted array of numbers
 * @returns {(Number|Boolean)} (wantedItem) index if it exist otherwise (false)
const BinarySearchAlgorithm = (wantedItem, sortedItems) => {
    let low = 0,
        high = items.length,
    while (low <= high) {
        // the mid can be a float num that's why I used Math.floor
        mid = Math.floor((high + low) / 2);
        if (wantedItem == items[mid]) return mid;
        if (wantedItem < items[mid]) {
            // eliminate right half
            high = mid - 1;
        } else {
            // eliminate left half
            low = mid + 1;
    // if the wanted item dosen't exist
    return false;
Enter fullscreen mode Exit fullscreen mode

Thank you so much for your time! Have a good day;

Top comments (0)

Visualizing Promises and Async/Await 🤯

async await

☝️ Check out this all-time classic DEV post