-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfindfirstandlastposition.cpp
55 lines (51 loc) · 1.14 KB
/
findfirstandlastposition.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
54
55
#include<iostream>
using namespace std;
int first_occurence(int arr[],int n,int key){
int start=0;
int end=n-1;
int mid;
int ans=-1;
mid=start+(end-start)/2;
while(start<=end){
if(key==arr[mid]){
ans=mid;
end=mid-1;
}
else if(key>arr[mid]){
start=mid+1;
}
else{
end=mid-1;
}
mid=start+(end-start)/2;
}
return ans;
}
int last_occurence(int arr[],int n,int key){
int start=0;
int end=n-1;
int mid;
int ans=-1;
mid=start+(end-start)/2;
while(start<=end){
if(key==arr[mid]){
ans=mid;
start=mid+1;
}
else if(key>arr[mid]){
start=mid+1;
}
else{
end=mid-1;
}
mid=start+(end-start)/2;
}
return ans;
}
int main(){
int arr1[6]={1,2,3,4,4,6};
int answer=first_occurence(arr1,6,4);
cout<<"the first occurence is :"<<answer<<endl;
int solution=last_occurence(arr1,6,4);
cout<<"the last occurence is :"<<solution<<endl;
}