Binary search in an array

Find the first zero based index of number > = given number in a sorted array
example:
1,2,5,5,5,6,7

4 => index 2
5 => index 2
2 => 1

C++:
01 int firstLarger(int *A, int size, int k)
02 {
03     int left=0;
04     int right=size1;
05     while(left<right){
06         int mid=(left+right)/2;
07         if(A[mid]>=k)
08             right=mid;
09         else
10             left=mid+1;
11     }
12     return right;
13 }
Advertisements
This entry was posted in Array and linked list, Binary search. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s