- Notifications
You must be signed in to change notification settings - Fork 363
Expand file tree
/
Copy pathJumpSearch.java
More file actions
Latest commit
51 lines (42 loc) · 1.55 KB
/
Copy pathJumpSearch.java
File metadata and controls
51 lines (42 loc) · 1.55 KB
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
// Java implementation of Jump Search Algorithm
importjava.util.*;
publicclassJumpSearch {
publicstaticintjumpSearch(int[] array, intsize, intkey) {
intstart = 0;
intend = (int)Math.sqrt(size); // the square root of array length
while (array[end] <= key && end < size) {
start = end; // if it is not the correct block then shift block
end += (int)Math.sqrt(size);
if (end > size - 1) {
end = size; // if right exceeds then bound the range
}
}
// perform linear search in selected block
for (inti = start; i < end; i++) {
if (array[i] == key) {
returni; // the correct position of the key
}
}
return -1;
}
publicstaticvoidmain(String[] args) {
Scannersc = newScanner(System.in);
//taking input of number of elements and key
intn = sc.nextInt();
intkey = sc.nextInt();
int[] arr = newint[n]; // create an array of size n
// taking input of array elements
for (inti = 0; i < n; i++) {
arr[i] = sc.nextInt();
}
// function call
intind = jumpSearch(arr, n, key);
if (ind >= 0) { // key is present in the array
System.out.println("Key found at location: " + ind);
}
else { // key is not present in the array
System.out.println("Key not found in the array");
}
sc.close();
}
}