Document

Binary Search

Binary search is a fast algorithm used to find a target value within a Sorted Array by repeatedly dividing the search interval in half. It compares the target value with the middle element of the array and continues narrowing down the search until the value is found or the interval is empty.






Algorithm Visualization
-84 -51 -12 0 5 14 19 27 59 45 48 71 100 124 190 227 280 299 550








Complexity

Worst Case O( log n )
Average Case O( log n )
Best Case O( 1 )
int binarySearch(int arr[], int low, int high, int x) {
    while (low <= high) {
        int mid = low + (high - low) / 2;
        
        if (arr[mid] == x)
            return mid;
        
        if (arr[mid] < x)
            low = mid + 1;
        else
            high = mid - 1;
    }
    
    return -1;
}

int main(void) {
    int arr[] = { 2, 3, 4, 10, 40 };
    int n = sizeof(arr) / sizeof(arr[0]);
    int x = 10;
    int result = binarySearch(arr, 0, n - 1, x);
    if(result==-1)
        printf("Element is not present in array\n");
    else
        printf("Element is present at index %d\n", result);
    return 0;
}
    
class BinarySearch {

    int binarySearch(int arr[], int x) {
        int low = 0, high = arr.length - 1;
        while (low <= high) {
            int mid = low + (high - low) / 2;
            if (arr[mid] == x)
                return mid;
            if (arr[mid] < x)
                low = mid + 1;
            else
                high = mid - 1;
        }
        return -1;
    }

    public static void main(String args[]) {
        BinarySearch ob = new BinarySearch();
        int arr[] = { 2, 3, 4, 10, 40 };
        int n = arr.length;
        int x = 10;
        int result = ob.binarySearch(arr, x);
        if (result == -1)
        System.out.println("Element is not present in array");
        else
        System.out.println("Element is present at index " + result);
    }
}

    
def binarySearch(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

if __name__ == '__main__':
    arr = [2, 3, 4, 10, 40]
    x = 10
    result = binarySearch(arr, 0, len(arr)-1, x)
    if result != -1:
        print("Element is present at index", result)
    else:
        print("Element is not present in array")