About Binary Search in Simple Terms

About Binary Search in Simple Terms

It’s a way to find specific value in a sorted array. It’s a lot faster that just looking through every single element one by one.

Difference between Linear and Binary Search

How does it work ?

  1. First, you pick the middle number of the list.

  2. If the number you're looking for is higher than the middle number, you know it's in the right half of the list. So you repeat the process on the right half of the list.

  3. If the number you're looking for is lower than the middle number, you know it's in the left half of the list. So you repeat the process on the left half of the list.

How to write code for that algorithm?

public int binarySearch(int[] array, int target) {

    // Initialize low and high pointers
    int low = 0;
    int high = array.length - 1;

 // Keep searching as long as low pointer is less than or equal to high pointer
    while (left <= right) {
        // Calculate middle index
        int mid = low + ( high - low) / 2;

        // Check if the middle element is equal to the target
        if (array[mid] == target) {
            return mid;
        }
         // If the middle element is less than the target, update low pointer to be one index to the high of the middle
        if (array[mid] < target) {
            low = mid + 1;
        // If the middle element is greater than the target, update high pointer to be one index to the low of the middle
        } else {
            high = mid - 1;
        }
    }
    return -1; // target not found
}

Code for Binary Search

Visualization of Binary Search

Visualization of Binary Search