Skip to content

Commit 8a4959e

Browse files
authored
feat: add ternary search on integers implementation
1 parent 8105816 commit 8a4959e

File tree

3 files changed

+21
-0
lines changed

3 files changed

+21
-0
lines changed
Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
int64_t ternary_search(const function<int64_t(int64_t)> &func, int64_t low,
2+
int64_t high) {
3+
4+
while (high - low > 2) {
5+
int64_t delta = (high - low) / 3LL;
6+
int64_t m1 = low + delta, m2 = high - delta;
7+
8+
if (func(m1) > func(m2)) { // change to < to find the maximum
9+
low = m1;
10+
} else {
11+
high = m2;
12+
}
13+
}
14+
int64_t best = NEUTRO;
15+
for (int64_t mid = low; mid <= high; ++mid) {
16+
best = min(best, func(mid));
17+
}
18+
return best;
19+
}
20+
// Usage:
21+
// int64_t best = ternary_search(funct, low, high);

0 commit comments

Comments
 (0)