Skip to content

Commit de04fc1

Browse files
committed
Add Jump Search algorithm in searching/jump_search.cpp
1 parent f1eddf4 commit de04fc1

File tree

1 file changed

+40
-0
lines changed

1 file changed

+40
-0
lines changed

searching/jump_search.cpp

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
#include <iostream>
2+
#include <vector>
3+
#include <cmath>
4+
using namespace std;
5+
6+
/**
7+
* @brief Performs Jump Search on a sorted vector.
8+
*
9+
* @param arr The sorted vector to search in.
10+
* @param target The value to search for.
11+
* @return Index of target if found, else -1.
12+
*/
13+
int jump_search(const vector<int>& arr, int target) {
14+
int n = arr.size();
15+
int step = sqrt(n);
16+
int prev = 0;
17+
18+
while (arr[min(step, n) - 1] < target) {
19+
prev = step;
20+
step += sqrt(n);
21+
if (prev >= n) return -1;
22+
}
23+
24+
for (int i = prev; i < min(step, n); i++) {
25+
if (arr[i] == target) return i;
26+
}
27+
28+
return -1;
29+
}
30+
31+
int main() {
32+
vector<int> arr = {1, 3, 5, 7, 9, 13, 17, 21};
33+
int target = 13;
34+
int result = jump_search(arr, target);
35+
if (result != -1)
36+
cout << "Found at index: " << result << endl;
37+
else
38+
cout << "Not found" << endl;
39+
return 0;
40+
}

0 commit comments

Comments
 (0)