AlgoPlus v0.1.0
Loading...
Searching...
No Matches
interpolation_search.h
1#ifndef INTERPOLATION_SEARCH_H
2#define INTERPOLATION_SEARCH_H
3
4#ifdef __cplusplus
5#include <algorithm>
6#include <cstdint>
7#include <vector>
8#endif
9
29template <typename Iterator, typename T>
30int64_t interpolation_search(Iterator begin, Iterator end, T key) {
31 auto size = std::distance(begin, end);
32
33 auto it_begin = begin;
34 auto it_end = end - 1;
35
36 while (size > 0 && *it_begin <= key && *it_end >= key) {
37 auto guess = it_begin;
38 if (*it_end != *it_begin) {
39 auto offset = static_cast<int>(static_cast<double>(size - 1) * (key - *it_begin) /
40 (*it_end - *it_begin));
41 std::advance(guess, offset);
42 }
43 if (*guess == key) {
44 return std::distance(begin, guess);
45 }
46
47 if (*guess > key) {
48 it_end = guess - 1;
49 } else {
50 it_begin = guess + 1;
51 }
52 size = std::distance(it_begin, it_end) + 1;
53 }
54
55 return static_cast<int64_t>(-1);
56}
57
58#endif // INTERPOLATION_SEARCH_H
@ key
the parser read a key of a value in an object
Definition json.hpp:11716