TheAlgorithms/C++ 1.0.0
All the algorithms implemented in C++
Loading...
Searching...
No Matches
jump_search.cpp
Go to the documentation of this file.
1
6#include <algorithm>
7#include <cmath>
8#include <iostream>
9
12int jumpSearch(int arr[], int x, int n) {
13 // Finding block size to be jumped
14 int step = std::sqrt(n);
15
16 // Finding the block where element is
17 // present (if it is present)
18 int prev = 0;
19 while (arr[std::min(step, n) - 1] < x) {
20 prev = step;
21 step += std::sqrt(n);
22 if (prev >= n)
23 return -1;
24 }
25
26 // Doing a linear search for x in block
27 // beginning with prev.
28 while (arr[prev] < x) {
29 prev++;
30
31 // If we reached next block or end of
32 // array, element is not present.
33 if (prev == std::min(step, n))
34 return -1;
35 }
36 // If element is found
37 if (arr[prev] == x)
38 return prev;
39
40 return -1;
41}
42
43// Driver program to test function
44int main() {
45 int arr[] = {0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610};
46 int x = 55;
47 int n = sizeof(arr) / sizeof(arr[0]);
48
49 // Find the index of 'x' using Jump Search
50 int index = jumpSearch(arr, x, n);
51
52 // Print the index where 'x' is located
53 std::cout << "\nNumber " << x << " is at index " << index;
54 return 0;
55}
int main()
Main function.
int jumpSearch(int arr[], int x, int n)