-
Notifications
You must be signed in to change notification settings - Fork 0
/
first&last_occurence.cpp
81 lines (70 loc) · 1.86 KB
/
first&last_occurence.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
73
74
75
76
77
78
79
80
81
/*
Program to find first and last occurence(index) of the specified element in an entered array
also helpfull to find no of occurences of specified element by performing the following operation => { (last occ) - (first occ) + 1 }
*/
#include<bits/stdc++.h>
using namespace std;
scanarray(int ar[], int n){
cout<<"Enter elements in array\n";
for(int i=0; i<n; i++){
cin>>*(ar+i);
}
}
printarray(int ar[], int n){
for(int i=0; i<n; i++){
cout<<*(ar+i)<<" ";
}
}
frmstart(int ar[], int n, int key){
int s = 0, e = n-1, mid, ans;
mid = s + (e-s)/2;
while(s<=e){
if(ar[mid]==key){
ans=mid;
e = mid-1;
}
else if(ar[mid]>key){
e = mid-1;
}
else if(ar[mid]<key){
s = mid+1;
}
mid = s + (e-s)/2;
}
return ans;
}
frmend(int ar[], int n, int key){
int s = 0, e = n-1, mid, ans;
mid = s + (e-s)/2;
while(s<=e){
if(ar[mid]==key){
ans=mid;
s = mid+1;
}
else if(ar[mid]>key){
e = mid-1;
}
else if(ar[mid]<key){
s = mid+1;
}
mid = s + (e-s)/2;
}
return ans;
}
int main(){
int *ar, n, key;
cout<<"Enter size of array\n";
cin>>n;
ar = (int*)malloc(n*sizeof(int));
scanarray(ar, n);
cout<<"Initial array\n";
printarray(ar, n);
cout<<"\nEnter key value\n";
cin>>key;
pair<int, int> p;
p.first = frmstart(ar, n, key);
p.second = frmend(ar, n, key);
cout<<"first occuring index of key = "<<p.first<<endl;
cout<<"last occuring index of key = "<<p.second<<endl;
return 0;
}