AlgoPlus v0.1.0
Loading...
Searching...
No Matches
binary_search.h
1#ifndef BINARY_SEARCH_H
2#define BINARY_SEARCH_H
3
4#ifdef __cplusplus
5#include <cstdint>
6#include <iostream>
7#include <vector>
8#endif
9
20template <typename T> int64_t bin_search(std::vector<T> arr, int64_t left, int64_t right, T x) {
21 while (left <= right) {
22 int64_t mid = left + (right - left) / 2;
23 if (arr[mid] == x) {
24 return mid;
25 }
26 if (arr[mid] < x) {
27 left = mid + 1;
28 } else {
29 right = mid - 1;
30 }
31 }
32 return -1; // element not found
33}
34
44template <typename T> int64_t lower_bound(std::vector<T> arr, int64_t left, int64_t right, T x) {
45 int64_t result = right, mid = 0;
46 --right;
47
48 while (left <= right) {
49 mid = left + (right - left) / 2;
50 if (arr[mid] >= x) {
51 result = mid;
52 // look for smaller index on the left
53 right = mid - 1;
54 } else {
55 left = mid + 1; // look on the right
56 }
57 }
58 return result;
59}
60
70template <typename T> int64_t upper_bound(std::vector<T> arr, int64_t left, int64_t right, T x) {
71 int64_t result = right, mid = 0;
72 --right;
73
74 while (left <= right) {
75 mid = left + (right - left) / 2;
76 if (arr[mid] > x) {
77 result = mid;
78 // look for smaller index on the left
79 right = mid - 1;
80 } else {
81 left = mid + 1; // look on the right
82 }
83 }
84 return result;
85}
86
87#endif