AlgoPlus v0.1.0
Loading...
Searching...
No Matches
ternary_search.h
1#ifndef TERNARY_SEARCH_H
2#define TERNARY_SEARCH_H
3
4#ifdef __cplusplus
5#include <algorithm>
6#include <cstdint>
7#include <iostream>
8#include <vector>
9#endif
10
11namespace {
30template <typename Iter, typename T> Iter ternary_search(Iter first, Iter last, T value) {
31 while (first < last) {
32 typedef typename std::iterator_traits<Iter>::difference_type diff_t;
33 diff_t diff = std::distance(first, last) / 3;
34 Iter mid1 = first + diff;
35 Iter mid2 = mid1 + diff;
36
37 if (*mid1 == value)
38 return mid1; // Found value
39 else if (*mid2 == value)
40 return mid2; // Found value
41
42 if (value < *mid1)
43 last = mid1;
44 else if (value > *mid2)
45 first = mid2 + 1;
46 else {
47 first = mid1 + 1;
48 last = mid2;
49 }
50 }
51 return last; // Not found
52}
53} // namespace
70template <typename Container, typename T> int64_t ternary_search(Container& c, const T& value) {
71 auto it = ternary_search(c.begin(), c.end(), value);
72 if (it != c.end() && *it == value)
73 return static_cast<int64_t>(std::distance(c.begin(), it));
74 else
75 return -1;
76}
77
78#endif // TERNARY_SEARCH_H