Sources:

https://www.youtube.com/watch?v=j5uXyPJ0Pew&vl=en

https://www.youtube.com/watch?v=P3YID7liBug

http://www.geeksforgeeks.org/binary-search/

Given a sorted array arr[] of n elements, write a function to search a given element x in arr[].

A simple approach is to dolinear search.The time complexity of above algorithm is O(n). Another approach to perform the same task is using Binary Search.

Binary Search: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.

The idea of binary search is to use the information that the array is sorted and reduce the time complexity to O(Log(n)).

Best case : O(1)

Worst Case: O(Log(n)).

Pseudo code:

Iterative Pseudocode

BinarySearch(array, array.len, element){
    start = 0
    end = array.len - 1
    while(start <= end){
        mid = (start+end)/2

        if(array[mid] == element)
            return mid
        else if(element < array[mid]){
            end = mid -1
        }
        else{
            start = mid + 1
        }
    }
    return -1
}

results matching ""

    No results matching ""