-
Notifications
You must be signed in to change notification settings - Fork 0
/
First Occur Last Occur.cpp
53 lines (46 loc) · 1.03 KB
/
First Occur Last Occur.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
*******************************************************************************/
#include <iostream>
using namespace std;
int firstIndex(int a[],int k,int n){
int start=0;
int end=n-1;
int mid=0;
int focc,locc=-1;
while(start<=end){
mid=start + (end-start)/2;
if(a[mid]==k){
focc=mid;
end=mid-1;
}else if(a[mid]>k){
end=mid-1;
}else{
start=mid+1;
}
}return focc;
}
int lastIndex(int a[],int k,int n){
int start=0;
int end=n-1;
int mid=0;
int locc=-1;
while(start<=end){
mid=start + (end-start)/2;
if(a[mid]==k){
locc=mid;
start=mid+1;
}else if(a[mid]>k){
end=mid-1;
}else{
start=mid+1;
}
}return locc;
}
int main()
{
int a[]={2,3,5,5,5,8,10};
int n=sizeof(a)/sizeof(a[0]);
int k=5;
cout<<"Occurence of "<<k<< " is from "<<firstIndex(a,k,n)<<" ";
cout<<"to "<<lastIndex(a,k,n);
return 0;
}