TheAlgorithms/C++ 1.0.0
All the algorithms implemented in C++
Loading...
Searching...
No Matches
jump_search.cpp File Reference

C++ program to implement Jump Search More...

#include <algorithm>
#include <cmath>
#include <iostream>
Include dependency graph for jump_search.cpp:

Go to the source code of this file.

Functions

int jumpSearch (int arr[], int x, int n)
 
int main ()
 

Detailed Description

C++ program to implement Jump Search

Definition in file jump_search.cpp.

Function Documentation

◆ jumpSearch()

int jumpSearch ( int arr[],
int x,
int n )

jump search implementation

Definition at line 12 of file jump_search.cpp.

12 {
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}

◆ main()

int main ( void )

Definition at line 44 of file jump_search.cpp.

44 {
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 jumpSearch(int arr[], int x, int n)