-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathprogram23.cpp
More file actions
77 lines (66 loc) · 1.59 KB
/
program23.cpp
File metadata and controls
77 lines (66 loc) · 1.59 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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
// (1). last and first occurence of an element in an array BY USING BINARY SEARCH
// (2). After this you print the number of ocxcurence
#include<iostream>
#include<algorithm>
using namespace std;
int firstoccurence(int arr[],int n,int key){
int s = 0;
int e = n-1;
int mid = s + (e-s)/2;
while(s<=e){
if(arr[mid]==key){
e = mid - 1;
}
else if(arr[mid]>key){
e = mid - 1;
}
else if(arr[mid]<key){
s = mid + 1;
}
mid = s + (e-s)/2;
}
return s ;
}
int lastoccurence(int arr[],int n, int key){
int s = 0;
int e = n-1;
int mid = s + (e-s)/2;
while(s<=e){
if(arr[mid] == key){
s = mid + 1;
}
else if(arr[mid]>key){
e = mid - 1;
}
else if(arr[mid]<key){
s = mid + 1;
}
mid = s + (e-s)/2;
}
return s-1;
}
int main(){
int n;
cout<<"Enter number of elements do you want to enter : ";
cin>>n;
int arr[n];
for(int i = 0;i<n;i++){
cin>>arr[i];
}
sort(arr,arr+n);
cout<<"your sorted array is [";
for(int i = 0;i<n;i++){
cout<<arr[i]<<" , ";
}
cout<<"]"<<endl;
int key;
cout<<"Enter the key element : ";
cin>>key;
int firstO = firstoccurence(arr,n,key);
int lastO = lastoccurence(arr,n,key);
int totalO = (lastO - firstO) + 1;
cout<<"first occurence is at index : "<<firstO<<endl;
cout<<"last occurence is at index : "<<lastO<<endl;
cout<<"total number of occurence : "<<totalO<<endl;
return 0;
}