forked from ash638/code-for-hactoberfest
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathoccurrence_element.cpp
More file actions
56 lines (49 loc) · 1.07 KB
/
occurrence_element.cpp
File metadata and controls
56 lines (49 loc) · 1.07 KB
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
56
#include<iostream>
#include<math.h>
using namespace std;
int first(int arr[],int n,int key){
int start=0;
int end=n-1;
int ans=-1;
int mid= start+(end-start)/2;
while(start<=end){
if(arr[mid]==key){
ans=mid;
end=mid-1;
}
if(arr[mid]>key){
end=mid-1;
}
else{
start=mid+1;
}
mid= start+ (end-start)/2;
}
return ans;
}
int last(int arr[],int n,int key){
int start=0;
int end=n-1;
int ans=-1;
int mid= start+(end-start)/2;
while(start<=end){
if(arr[mid]==key){
ans=mid;
start=mid+1;
}
else if(arr[mid]>key){
end=mid-1;
}
else if(arr[mid]<key){
start=mid+1;
}
mid= start+ (end-start)/2;
}
return ans;
}
int main(){
int arr[9]={1,2,3,3,4,4,5,6,7};
cout<<"index of first occurence is"<<first(arr,9,4)<<endl;
cout<<"index of last occurence is"<<last(arr,9,4);
return 0;
}