This post is completed by 3 users

  • 0
Add to List
Beginner

1. 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

Output:

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