Home » Data Structure & Algorithms » Binary Search

Binary Search

 


The binary search algorithm begins by comparing the target value to the value of the middle element of the sorted array. If the target value is equal to the middle element’s value, then the position is returned and the search is finished. If the target value is less than the middle element’s value, then the search continues on the lower half of the array; or if the target value is greater than the middle element’s value, then the search continues on the upper half of the array. This process continues, eliminating half of the elements, and comparing the target value to the value of the middle element of the remaining elements – until the target value is either found (and its associated element position is returned), or until the entire array has been searched (and “not found” is returned).The binary search algorithm can be classified as a divide and conquer search algorithm  and executes in logarithmic time with O(logn) time complexity.

Question :
There is a sorted array of integers.You are given an element.Search the element in the array in 0(log n) complexity and return its index.

Solution :
The problem is solved in both iterative and recursive way.

Algorithm :
int[] arr = { 2, 4, 6, 8, 10, 12, 14, 16, 18, 20 };
Suppose the element to be searched = 6
Step 1 : If the element to be searched is first compared with middle element.If it is equal to the middle element then return the middle element index.
Step 2 : If the element to be searched is greater than middle element search in the right sub array.If it is equal to less than middle element then search in left sub array.
Step 3 : If the element is not found then return -1 or print it is not found.

Program :

Output:

 


 


Leave a comment

Your email address will not be published. Required fields are marked *

5 + 2 =