File tree Expand file tree Collapse file tree 1 file changed +62
-0
lines changed Expand file tree Collapse file tree 1 file changed +62
-0
lines changed Original file line number Diff line number Diff line change
1
+ // C++ program to implement Jump Search
2
+ // Author Bharat Reddy
3
+
4
+ #include < bits/stdc++.h>
5
+ using namespace std ;
6
+
7
+ int jumpSearch (int arr[], int x, int n)
8
+ {
9
+ // Finding block size to be jumped
10
+ int step = sqrt (n);
11
+
12
+ // Finding the block where element is
13
+ // present (if it is present)
14
+ int prev = 0 ;
15
+ while (arr[min (step, n)-1 ] < x)
16
+ {
17
+ prev = step;
18
+ step += sqrt (n);
19
+ if (prev >= n)
20
+ return -1 ;
21
+ }
22
+
23
+ // Doing a linear search for x in block
24
+ // beginning with prev.
25
+ while (arr[prev] < x)
26
+ {
27
+ prev++;
28
+
29
+ // If we reached next block or end of
30
+ // array, element is not present.
31
+ if (prev == min (step, n))
32
+ return -1 ;
33
+ }
34
+ // If element is found
35
+ if (arr[prev] == x)
36
+ return prev;
37
+
38
+ return -1 ;
39
+ }
40
+
41
+ // Driver program to test function
42
+ int main ()
43
+ {
44
+ int n,i;
45
+ cout<<" Eneter size of array : " ;
46
+ cin>>n;
47
+ cout<<" Enter elements of array" <<endl;
48
+ int a[n];
49
+ for (i=0 ;i<n;i++)
50
+ cin>>a[i];
51
+ sort (a,a+n);
52
+ cout<<" Enter key to be searched : " ;
53
+ int key;
54
+ cin>>key;
55
+
56
+ // Find the index of 'x' using Jump Search
57
+ int index = jumpSearch (a, key, n);
58
+
59
+ // Print the index where 'x' is located
60
+ cout << " \n Number " << key << " is at index " << index;
61
+ return 0 ;
62
+ }
You can’t perform that action at this time.
0 commit comments