Ad

Tuesday 11 June 2013

Algo#11: Binary Search Technique with Duplicates - Find First Occurrence Index

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 (First Occurrence) in Sorted Array With Duplicates.
Step 1: Set l(left) at start index of array.Step 2: Set r(right) at end index of array.
Step 3: Set left-border at start index of array.
Step 4: Set right-border at end index of array.
Step 5: Repeat following until r>=l
        5.1: Initialize mid using current left and right index (l+(r-l)/2).
      5.2: If element at mid index is target element and element at before mid index is different than target element, then return mid index as successful binary search.
        5.3: Otherwise if element at mid index is greater or equal to target element, then replace r = mid -1
        5.4: Otherwise if element at mid index is less than target element, then replace l = mid +1
Step 6: 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