-
Notifications
You must be signed in to change notification settings - Fork 0
/
firstlastOcc.cpp
81 lines (73 loc) · 1.53 KB
/
firstlastOcc.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
#include<iostream>
using namespace std;
int firstOccurence (int arr[],int size,int key)
{
int start=0;
int end=size-1;
int mid=start+(end-start)/2;
int ans=-1;
while(start<=end)
{
if(arr[mid]==key)
{
ans=mid;
end=mid-1;
}
else if(arr[mid]>key)
{
end=end-1;
}
else if(arr[mid]<key)
{
start=mid+1;
}
mid=start+(end-start)/2;
}
return ans;
}
int lastOccurence (int arr[],int size,int key)
{
int start=0;
int end=size-1;
int mid=start+(end-start)/2;
int ans=-1;
while(start<=end)
{
if(arr[mid]==key)
{
ans=mid;
start=mid+1;
}
else if(arr[mid]>key)
{
end=end-1;
}
else if(arr[mid]<key)
{
start=mid+1;
}
mid=start+(end-start)/2;
}
return ans;
}
int input(int arr[],int size)
{
for(int i=0;i<size;i++)
{
cin>>arr[i];
}
}
int main()
{
cout<<"Enter the size of an Array you want to enter"<<endl;
int size;
cin>>size;
cout<<"Enter the Array"<<endl;
int arr[100];
input(arr,size);
cout<<"Enter the key you want to search"<<endl;
int key;
cin>>key;
cout<<"The First occurence of the key "<<firstOccurence(arr,size,key)<<endl;
cout<<"The last occurence of the key "<<lastOccurence(arr,size,key)<<endl;
}