Ad

Monday, 10 June 2013

Algo#10: Binary Search Technique

Binary search technique is very well known for its fast search result provided given array is sorted.

Following is simple iterative algorithm for Binary Search in Sorted Array.
Step 1: Set l(left) at start index of array.
Step 2: Set r(right) at end index of array.
Step 3: Repeat following until r>=l
        3.1: Initialize mid using current left and right index (l+(r-l)/2).
        3.2: If element at mid index is target element, then return mid index as successful binary search.
        3.3: Otherwise if element at mid index is greater than target element, then replace r = mid -1
        3.4: Otherwise if element at mid index is less than target element, then replace l = mid +1
Step 4: If you reach here, element you are searching for is not found.
Following is implementation of above algorithm in c language.





Please write comments if you find anything wrong or you want to add something more related to this topic.

No comments:

Post a Comment

Write your comment here.

Ad