-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathFirst_AND_Last_Occurence_of_An_Element_in_Array.cpp
More file actions
89 lines (70 loc) · 1.51 KB
/
First_AND_Last_Occurence_of_An_Element_in_Array.cpp
File metadata and controls
89 lines (70 loc) · 1.51 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
77
78
79
80
81
82
83
84
85
86
87
88
#include <iostream>
#include <bits/stdc++.h>
using namespace std;
int searchFirstIndex(int a[],int n,int x)
{
int start=0,pos=0,mid,end;
end = n;
if (n == 0)
return -1;
if(n == 1)
return 0;
while(start<=end)
{
mid = (start+end)/2;
if(x == a[mid])
{
pos = mid;
end = mid-1;
}
else if(x>a[mid])
start = mid+1;
else
end = mid-1;
}
return pos;
}
int searchLastIndex(int a[],int n,int x)
{
int start=0,pos=0,mid,end;
end = n;
if (n == 0)
return -1;
if(n==1)
return 0;
while(start<=end)
{
mid = (start+end)/2;
if(x == a[mid] )
{
pos = mid;
start = mid+1;
}
else if(x>a[mid])
start = mid+1;
else
end = mid-1;
}
return pos;
}
int main()
{
int t;
cout<<"Enter the no of test cases : "<<endl;
cin>>t;
while(t--)
{
int n,x;
cout<<"Enter the size of array : "<<endl;
cin>>n;
int a[n];
cout<<"Enter the elements of array : "<<endl;
for(int i=0;i<n;i++)
cin>>a[i];
cout<<"Enter the number that who's first and last occurence needs to be searched : "<<endl;
cin>>x;
cout<<"Last Occurence of the number is = "<<searchLastIndex(a,n,x)<<endl;
cout<<"First Occurence of the number is = "<<searchFirstIndex(a,n,x)<<endl;
}
return 0;
}