Skip to content

Commit 99cfd88

Browse files
authored
Merge pull request deutranium#209 from rcchcz/PR
Jump search in C++
2 parents eb9ab29 + f4e602e commit 99cfd88

File tree

1 file changed

+48
-0
lines changed

1 file changed

+48
-0
lines changed
+48
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
#include <iostream>
2+
#include <vector>
3+
#include <cmath>
4+
#include <algorithm>
5+
6+
/**
7+
* Jump search function.
8+
*
9+
* @param v Sorted vector on which the search will be performed.
10+
* @param x Element to be searched.
11+
* @return Element index if found; -1 otherwise.
12+
*/
13+
int jumpSearch(const std::vector<long int> &v, long int x) {
14+
int n = v.size(); // number of elements
15+
int jump = std::sqrt(n); // block size to jump
16+
17+
// search for the block the element may be in
18+
int prev = 0;
19+
while(jump < n && v[jump] <= x) {
20+
prev = jump; // jump to next block
21+
jump += std::sqrt(n);
22+
if(prev >= n) return -1; // vector size exceeded
23+
}
24+
25+
// linear search through the block
26+
while(prev < jump) {
27+
if(v[prev] == x) return prev; // element found
28+
prev++;
29+
}
30+
31+
return -1; // not found
32+
}
33+
34+
/**
35+
* Driver code.
36+
*/
37+
int main() {
38+
// sorted vector on which the search will be performed; [0, 30]
39+
std::vector<long int> v = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30};
40+
long int x = 7; // element to be searched
41+
int index = jumpSearch(v, x);
42+
43+
if(index != -1) std::cout << "Element found at index " << index;
44+
else std::cout << "Element not found";
45+
std::cout << std::endl;
46+
47+
return 0;
48+
}

0 commit comments

Comments
 (0)