-
Notifications
You must be signed in to change notification settings - Fork 2
/
FirstandLastOcc.cpp
79 lines (59 loc) · 1.34 KB
/
FirstandLastOcc.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
#include<iostream>
using namespace std;
int firstOcc(int arr[] , int n , int k){
int start = 0;
int end = n-1;
int ans = -1;
//find mid of the array
int mid = start +(end-start)/2;
while (start <= end)
{
if(arr[mid]== k){
ans = mid;
end =mid-1;
}
else if(k > arr[mid]){
start =mid+1;
}
else if(k < arr[mid]){
end =mid-1;
}
mid = start +(end-start)/2;
};
return ans;
};
int lastOcc(int arr[] , int n , int k){
int start = 0;
int end = n-1;
int ans =-1;
//find mid of the array
int mid = start +(end-start)/2;
while (start <= end)
{
if(arr[mid]== k){
ans = mid;
start =mid+1;
}
else if(k > arr[mid]){
start =mid+1;
}
else if(k < arr[mid]){
end =mid-1;
}
mid = start +(end-start)/2;
};
return ans;
};
int main(){
int odd[5] = {1,2,3,3,5};
int even[6] = {2,4,4,4,4,8};
int oddfirst = firstOcc(odd ,5 , 3);
int oddlast = lastOcc(odd ,5 , 3);
int evenfirst =firstOcc(even ,6,4);
int evenlast =lastOcc(even ,6,4);
cout<< "First Index of 3 is " << oddfirst<<endl;
cout<< " last index of 3 is " << oddlast <<endl;
cout<< "First Index of 4 is " << evenfirst<<endl;
cout<< " last index of 4 is " << evenlast <<endl;
return 0;
}