aboutsummaryrefslogtreecommitdiff
path: root/impls/bsearch.cpp
blob: cc7b8e868b77f4b48fe6d39b67b21eed636b8b60 (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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
/* bsearch.cpp
 * Created: 2023-07-10
 * Author: Aryadev Chavali
 */

#include <algorithm>
#include <cassert>
#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;

ostream &print_arr(ostream &os, std::vector<int> &arr)
{
  os << "[";
  for (size_t i = 0; i < arr.size(); ++i)
    os << arr[i] << (i == arr.size() - 1 ? "" : ",");
  return os << "]";
}

int bsearch(int n, std::vector<int> arr)
{
  int l = 0;
  int u = arr.size() - 1;
  while (l <= u)
  {
    int midpoint = l + ((u - l) / 2);
    int val      = arr[midpoint];

    if (val == n)
    {
      return midpoint;
    }
    else if (val > n)
    {
      u = midpoint - 1;
    }
    else
    {
      l = midpoint + 1;
    }
  }
  return -1;
}

int main(int argc, char *argv[])
{
  std::ifstream input(argc > 1 ? argv[1] : "bsearch.txt");
  std::vector<int> arr;

  for (std::string line; std::getline(input, line);
       arr.push_back(std::stoi(line)))
    continue;

  std::sort(std::begin(arr), std::end(arr));

  for (size_t i = 0; i < arr.size(); ++i)
  {
    int index = bsearch(arr[i], arr);
    assert(index == (int)i);
  }
  return 0;
}