forked from shivam-0510-zz/Cpp-codes
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcountOccurence.cpp
More file actions
54 lines (54 loc) · 1.31 KB
/
countOccurence.cpp
File metadata and controls
54 lines (54 loc) · 1.31 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
#include<iostream>
using namespace std;
int first_Occ(int arr[],int n,int low,int high,int key ){
while(low<=high){
int mid = (low+high)/2;
if(arr[mid]>key){
return first_Occ(arr,n,low,mid-1,key);
}
else if(arr[mid]<key){
return first_Occ(arr,n,mid+1,high,key);
}
else{
if(mid==0 || arr[mid]!=arr[mid-1])
return mid;
else
return first_Occ(arr,n,low,mid-1,key);
}
}
return -1;
}
int last_Occ(int arr[],int n,int low,int high,int key){
while(low<=high){
int mid=(low+high)/2;
if(arr[mid]>key)
return last_Occ(arr,n,low,mid-1,key);
else if(arr[mid]<key)
return last_Occ(arr,n,mid+1,high,key);
else{
if(mid==n-1 || arr[mid]!=arr[mid+1])
return mid;
else
return last_Occ(arr,n,mid+1,high,key);
}
}
return -1;
}
int countOcc(int arr[],int n,int key){
int first = first_Occ(arr,n,0,n-1,key);
if(first==-1)
return 0;
else
return (last_Occ(arr,n,0,n-1,key)-first+1);
}
int main(){
int n;
cin>>n;
int arr[n];
for(int i=0;i<n;i++)
cin>>arr[i];
int key;
cin>>key;
cout<<countOcc(arr,n,key);
return 0;
}