Ready — enter array elements to build the list
Speed
🎨 Customize Colors
Scene Background
Element Color
Text Color
Found/Pointer Color

🔍 Binary Search

Binary Search is an efficient algorithm for finding an item from a sorted list of items. It works by repeatedly dividing in half the portion of the list that could contain the item, until you've narrowed down the possible locations to just one.

⏱ Best Case: O(1) ⏱ Average Case: O(log n) ⏱ Worst Case: O(log n) 💾 Space: O(1)
Python
def binary_search(arr, low, high, x):
    while low <= high:
        mid = low + (high - low) // 2

        if arr[mid] == x:
            return mid

        elif arr[mid] < x:
            low = mid + 1

        else:
            high = mid - 1
            
    return -1
JavaScript
function binarySearch(arr, x) {
    let low = 0;
    let high = arr.length - 1;

    while (low <= high) {
        let mid = Math.floor(low + (high - low) / 2);

        if (arr[mid] === x) return mid;

        if (arr[mid] < x) {
            low = mid + 1;
        } else {
            high = mid - 1;
        }
    }

    return -1;
}