forked from AllAlgorithms/cpp
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathjump_search.cpp
62 lines (53 loc) · 1.34 KB
/
jump_search.cpp
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
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
// C++ program to implement Jump Search
//Author Bharat Reddy
#include <bits/stdc++.h>
using namespace std;
int jumpSearch(int arr[], int x, int n)
{
// Finding block size to be jumped
int step = sqrt(n);
// Finding the block where element is
// present (if it is present)
int prev = 0;
while (arr[min(step, n)-1] < x)
{
prev = step;
step += sqrt(n);
if (prev >= n)
return -1;
}
// Doing a linear search for x in block
// beginning with prev.
while (arr[prev] < x)
{
prev++;
// If we reached next block or end of
// array, element is not present.
if (prev == min(step, n))
return -1;
}
// If element is found
if (arr[prev] == x)
return prev;
return -1;
}
// Driver program to test function
int main()
{
int n,i;
cout<<"Eneter size of array : ";
cin>>n;
cout<<"Enter elements of array"<<endl;
int a[n];
for(i=0;i<n;i++)
cin>>a[i];
sort(a,a+n);
cout<<"Enter key to be searched : ";
int key;
cin>>key;
// Find the index of 'x' using Jump Search
int index = jumpSearch(a, key, n);
// Print the index where 'x' is located
cout << "\nNumber " << key << " is at index " << index;
return 0;
}