-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path42_firstAndLastOccurence.cpp
65 lines (58 loc) · 1.86 KB
/
42_firstAndLastOccurence.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
#include <iostream>
using namespace std;
// function to find the first occurence of the key
int firstOccurence(int arr[],int size,int key){
int start = 0;
int end = size-1;
int ans = -1;
int mid = start + (end-start)/2;
while(start<=end){
if(arr[mid] == key){
ans = mid;
end = mid-1;
}
else if(key > arr[mid]){
start = mid + 1;
}
else if(key < arr[mid]){
end = mid - 1;
}
mid = start + (end-start)/2;
}
return ans;
}
// function to find the last occurence of given key
int lastOccurence(int arr[],int size, int key){
int start = 0;
int end = size-1;
int ans = -1;
int mid = start + (end-start)/2;
while(start<=end){
if(arr[mid] == key){
ans = mid;
start = mid + 1;
}
else if(key > arr[mid]){
start = mid + 1;
}
else if(key < arr[mid]){
end = mid - 1;
}
mid = start + (end - start)/2;
}
return ans;
}
int main(){
// Here, in this, we are given a totally sorted array and given an element key. We have to find the first occurence and the last occurence of the given key and its total occurence in the whole array. Occurence is referred as the index on which it is present
int arr[] = {1,2,3,3,3,3,4,5};
cout<<"Array is: [1,2,3,3,3,3,4,5]"<<endl;
int key;
cout<<"Enter the key to find corresponding occurences: ";
cin>>key;
int firstOccurr = firstOccurence(arr,8,key);
int lastOccurr = lastOccurence(arr,8,key);
cout<<"First Occurence of given key is: "<<firstOccurr<<endl;
cout<<"Last Occurence of given key is: "<<lastOccurr<<endl;
cout<<"Total Occurence of given key is: "<<lastOccurr-firstOccurr+1<<endl;
return 0;
}