blob: 6172b1556fb34081e76898261b1e298e3387f01c (
plain)
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
|
/* bsearch.cpp
* Created: 2023-07-10
* Author: Aryadev Chavali
*/
#include <algorithm>
#include <cstdlib>
#include <fstream>
#include <iostream>
#include <string>
#include <vector>
using std::cin;
using std::cout;
using std::endl;
using std::ostream;
using std::string;
using std::vector;
vector<int> arr;
ostream &print_arr(ostream &os)
{
os << "[";
for (size_t i = 0; i < arr.size(); ++i)
os << arr[i] << (i == arr.size() - 1 ? "" : ",");
return os << "]";
}
int bsearch(int n, int l = 0, int u = arr.size() - 1)
{
int midpoint = ((u + l) / 2);
if (l >= u || u <= 0)
return -1;
int val = arr[midpoint];
if (val == n)
return midpoint;
else if (val > n)
return bsearch(n, l, midpoint - 1);
else
return bsearch(n, midpoint + 1, u);
}
int main(void)
{
std::ifstream input("bsearch.txt");
string line;
while (std::getline(input, line))
arr.push_back(std::stoi(line));
std::sort(std::begin(arr), std::end(arr));
string inp;
cout << "Enter number to search: ";
cin >> inp;
int to_search = std::stoi(inp);
cout << bsearch(to_search) << endl;
return 0;
}
|