Skip to content

Commit 4760d97

Browse files
SahilSahil
authored andcommitted
Added Range search problem in Binary Searching.
1 parent 00e927c commit 4760d97

File tree

2 files changed

+65
-0
lines changed

2 files changed

+65
-0
lines changed
Lines changed: 65 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,65 @@
1+
// Find the range of a particular element occuring in a given sorted array.
2+
// If the element doesn't exist, return 1.
3+
4+
#include <bits/stdc++.h>
5+
6+
using namespace std;
7+
8+
int findleft(const vector<int>& A, int B, int low, int high){
9+
int res = -1;
10+
while(low <= high){
11+
int mid = low + (high - low)/2;
12+
if(A[mid] == B){
13+
res = mid;
14+
high = mid-1;
15+
}else if(A[mid] < B){
16+
low = mid+1;
17+
}else high = mid-1;
18+
}
19+
if(res == -1)
20+
return res;
21+
return low;
22+
}
23+
24+
int findright(const vector<int>& A, int B, int low, int high){
25+
int res = -1;
26+
while(low <= high){
27+
int mid = low + (high - low)/2;
28+
if(A[mid] == B){
29+
res = mid;
30+
low = mid+1;
31+
}else if(A[mid] > B){
32+
high = mid-1;
33+
}else low = mid+1;
34+
}
35+
if(res == -1)return -1;
36+
return low-1;
37+
}
38+
39+
int main(int argc, char const *argv[])
40+
{
41+
std::vector<int> v({1,2,2,3,3,3,4,4,4,4,5,6,7,8,8,8,8,8});
42+
43+
cout << "The input vector is: " << endl;
44+
for(auto i: v){
45+
cout << i << " ";
46+
}
47+
cout << endl;
48+
49+
cout << "The first and last index of occurance of element '8' is : " << findleft(v, 8, 0, v.size()-1)
50+
<< " "
51+
<< findright(v, 8, 0, v.size()-1)
52+
<< endl;
53+
54+
cout << "The first and last index of occurance of element '1' is : " << findleft(v, 1, 0, v.size()-1)
55+
<< " "
56+
<< findright(v, 1, 0, v.size()-1)
57+
<< endl;
58+
59+
cout << "The first and last index of occurance of element '10' is : " << findleft(v, 10, 0, v.size()-1)
60+
<< " "
61+
<< findright(v, 10, 0, v.size()-1)
62+
<< endl;
63+
64+
return 0;
65+
}

Searching/binary search/cpp/a.exe

81 KB
Binary file not shown.

0 commit comments

Comments
 (0)