Binary Search

Objective : Write an algorithm to find an element in an sorted array

Input: A sorted array, arrA[] and an key

Output : Return true if element is found, else false.

Approach: The idea is to compare the middle element of array with the key, if key equal to the middle element , that’s it you have find your element, return true. If key is greater than the middle element, chuck out the first half of the array, you wont find your key in the first half and do the recursive search on the right half of the array and vice versa.

If(mid_element==key)
  return true;
else if (mid>key)
  do recursive search on the right half of the array.
else
 do recursive search on the left half of the array.

Time Complexity: O(logN) –since we are eliminating half of the array with every comparison.

Binary Search

Binary Search

Complete Code:


Output:

The 99 present in array a ??? :true
The 76 present in array a ??? :false

 

__________________________________________________
Top Companies Interview Questions..-

Google Microsoft Amazon Facebook more..

If you find anything incorrect or you feel that there is any better approach to solve the above problem, please write comment.
__________________________________________________

  • Vince Lieu

    if (mid>key)
    do recursive search on the left half of the array.

    else
    do recursive search on the right half of the array.

  • Archit

    // Generic way to binary search any object types
    public int binarySearch(Object[] a, Object key) {
    // if(Objects.isNull(a) || Objects.isNull(key)) throw new IllegalArgumentException(“Invalid arguments”);
    int low = 0;
    int high = a.length-1;
    int mid ;

    while (low >> 1;
    Comparable midVal = (Comparable) a[mid];
    int cmp = midVal.compareTo(key);
    if(cmp 0) {
    high = mid-1;
    }
    else {
    return mid;
    }
    }
    return – (low+1);
    }

%d bloggers like this: