Skip to content

Commit 60cd714

Browse files
authored
jumpSearch.cpp
1 parent 35e86b1 commit 60cd714

File tree

1 file changed

+36
-0
lines changed

1 file changed

+36
-0
lines changed

searching/jumpSearch.cpp

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
#include <bits/stdc++.h>
2+
using namespace std;
3+
4+
int jumpSearch(int arr[], int x, int n)
5+
{
6+
// Finding block size to be jumped
7+
int step = sqrt(n);
8+
9+
// Finding the block where element is
10+
// present (if it is present)
11+
int prev = 0;
12+
while (arr[min(step, n)-1] < x)
13+
{
14+
prev = step;
15+
step += sqrt(n);
16+
if (prev >= n)
17+
return -1;
18+
}
19+
20+
// Doing a linear search for x in block
21+
// beginning with prev.
22+
while (arr[prev] < x)
23+
{
24+
prev++;
25+
26+
// If we reached next block or end of
27+
// array, element is not present.
28+
if (prev == min(step, n))
29+
return -1;
30+
}
31+
// If element is found
32+
if (arr[prev] == x)
33+
return prev;
34+
35+
return -1;
36+
}

0 commit comments

Comments
 (0)