-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfirstand_last_position.cpp
56 lines (49 loc) · 1.08 KB
/
firstand_last_position.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
#include<iostream>
using namespace std;
int firstposition(int arr[],int n,int key)
{
int start = 0;
int end = n-1;
int mid = start + (end-start)/2;
int ans = -1;
while(start<=end)
{
if(arr[mid]==key){
ans = mid;
end = mid -1;
}
if(arr[mid]<key)
start = mid+1;
if(arr[mid]>key)
end = mid - 1;
mid = start + (end-start)/2;
}
return ans ;
}
int lastposition(int arr[],int n,int key)
{
int start = 0;
int end = n-1;
int mid = start + (end-start)/2;
int ans = -1;
while(start<=end)
{
if(arr[mid]==key){
ans = mid;
start = mid +1;
}
if(arr[mid]<key)
start = mid+1;
if(arr[mid]>key)
end = mid - 1;
mid = start + (end-start)/2;
}
return ans ;
}
int main()
{
int arr[10]={3,3,3,3,3,3,3,3,3,3};
cout<<"First positon of 3 on index "<<firstposition(arr,10,3);cout<<endl;
cout<<"Last positon of 3 is "<<lastposition(arr,10,3);
return 0;
}