-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathNumberOfOccurencesInASortedArray.cpp
72 lines (67 loc) · 1.36 KB
/
NumberOfOccurencesInASortedArray.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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
#include <iostream>
using namespace std;
int firstoccurence(int arr[],int n,int key){
int start=0;
int end=n-1;
while(start<=end){
int mid=(start+end)/2;
if(key>arr[mid]){
start=mid+1;
}
else if(key<arr[mid]){
end=mid-1;
}
else{
if(n==0 || arr[mid-1]!=arr[mid]){
return mid;
}
else{
end=mid-1;
}
}
}
return -1;
}
int lastoccurence(int arr[],int n,int key){
int start=0;
int end=n-1;
while(start<=end){
int mid=(start+end)/2;
if(key>arr[mid]){
start=mid+1;
}
else if(key<arr[mid])
{
end=mid-1;
}
else{
if(mid==n-1 || arr[mid+1]!=arr[mid]){
return mid;
}
else{
start=mid+1;
}
}
}
return -1;
}
int occurences(int arr[],int n, int key){
int first=firstoccurence(arr,n,key);
int last=lastoccurence(arr,n,key);
int num=last-first+1;
if(num<0){
return -1;
}
else{
return num;
}
}
int main()
{
//Write a program to count number of occurences of an element in a sorted array
int arr[]={5,10,10,10,10,20,20};
int key=10;
int n=7;
cout<<occurences(arr,n,key)<<endl;
return 0;
}