First occurrence

Find the first occurrence of an integer in a sorted array.

C++:
01 int firstIndex(int *A, int size, int e)
02 {
03     int left=0;
04     int right=size1;
05     while(left<right){
06         int mid=(left+right)/2;
07         if(A[mid]>=e)
08             right=mid;
09         else if(A[mid]<e)
10             left=mid+1;
11     }
12     if(A[left]==e)
13         return left;
14     else
15         return 1;
16 }
Advertisements
This entry was posted in Array and linked list. 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