-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathJump_Search.cpp
59 lines (47 loc) · 865 Bytes
/
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
#include<iostream>
#include<cmath>
using namespace std;
int JumpSearch(int arr[], int n, int key){
int blocksize = sqrt(n);
int prev = 0 ;
int jumpcount = 0;
while (arr[min(blocksize, n) -1]< key)
{
prev = blocksize ;
blocksize += sqrt(n);
jumpcount++;
if (prev>=n)
{
return -1;
}
}
while (arr[prev]<key)
{
prev++;
jumpcount++;
if (prev==min(blocksize, n))
{
return -1;
}
}
if (arr[prev]==key)
{
jumpcount++;
cout<<"jump count: "<<jumpcount<<endl;
return prev;
}
return -1;
}
int main(){
int n;
cin>>n;
int arr[n];
for (int i = 0; i < n; i++)
{
cin>>arr[i];
}
int key;
cin>>key;
cout<<JumpSearch(arr,n , key)<<endl;
return 0;
}