AlgoPlus v0.1.0
Loading...
Searching...
No Matches
jump_search.h
1#ifndef JUMP_SEARCH_H
2#define JUMP_SEARCH_H
3
4#ifdef __cplusplus
5#include <cmath>
6#include <cstdint>
7#include <iostream>
8#include <vector>
9#endif
10
17template <typename T> int64_t jump_search(std::vector<T> arr, T key) {
18 int64_t n = arr.size(), step = sqrt(arr.size()), prev = 0;
19 while (arr[std::min(step, n) - 1] < key) {
20 prev = step;
21 step += sqrt(n);
22 if (prev >= n) {
23 return -1; // out of bounds
24 }
25 }
26 while (arr[prev] < key) {
27 prev++;
28 if (prev == std::min(step, n)) {
29 return -1;
30 }
31 }
32 return (arr[prev] == key) ? prev : -1;
33}
34
35#endif