Categories

Binary Search Implementation in Javascript

 Suppose we have an array [1,2,3,4,5,6] and array is sorted in ascending order. Now we are asked to find the position of number 5 in the array using binary search. If number is found then return it’s index otherwise return -1;

Now let us see binary search algo.

So the idea behind binary search is to keep on dividing our array from it’s mid point and move either left or right of the mid point by incrementing low = mid+1 if our target is greater than arr[mid] otherwise 

decrementing from mid (high = mid-1)  if our target is less than arr[mid].

We will keep doing this until low <= high

Now let us understand thorough a picture.

Suppose we have to find index of number 5 in array [1,2,3,4,5,6] using binary search then we will do the following.

Here is the code in Javascript 

arr is [1,2,3,4,5,6]

n = length of array 

k = our target 5

function binarysearch(arr, n, k) {
        
        let low =arr[0];
        let high = arr[n-1];
        
        while(low <= high){
            
            let mid = Math.floor((low + high) / 2);
            
            if(arr[mid]== k)
            return mid;
            
            if(k >arr[mid]){
                low = mid+1;
            }else{
                
                high = mid-1;
            }
            
        }
        return -1;
    }

We will get 4 as the mid of 5 

adbanner