-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathArray_First_Last_position.cpp
More file actions
76 lines (59 loc) · 1.31 KB
/
Array_First_Last_position.cpp
File metadata and controls
76 lines (59 loc) · 1.31 KB
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
// Q) First and Last Position of an Element In Sorted Array.
#include<iostream>
using namespace std;
First_position(int arr[],int size,int key)
{
int ans=0;
int start=0 , end=size-1;
int mid = start + (end-start)/2;
while (start<=end)
{
if (arr[mid] == key)
{
end=mid-1;
ans=mid;
}
else if(arr[mid] < key)
{
start=mid+1;
}
else{
end=mid-1;
}
mid= start + (end-start)/2;
}
return ans;
}
Last_position(int arr[],int size,int key)
{
int ans=0;
int start=0 , end=size-1;
int mid = start + (end-start)/2;
while (start<=end)
{
if (arr[mid] == key)
{
start=mid+1;
ans=mid;
}
else if(arr[mid] < key)
{
start=mid+1;
}
else{
end=mid-1;
}
mid= start + (end-start)/2;
}
return ans;
}
int main()
{
int odd[7]={1,2,2,2,2,3,3};
// pair<int,int> p; (another feature)
// p.first=First_position(odd,7,2);
// p.second=First_position(odd,7,2);
cout<<"the first occurence of 2 is "<<First_position(odd,7,2)<<endl;
cout<<"the last occurence of 2 is "<<Last_position(odd,7,2);
return 0;
}