forked from anku580/Java-Algorithms
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathJumpSearch.java
More file actions
63 lines (57 loc) · 1.6 KB
/
JumpSearch.java
File metadata and controls
63 lines (57 loc) · 1.6 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
52
53
54
55
56
57
58
59
60
61
62
63
package searching;
import java.util.*;
public class JumpSearch
{
public static void main( String args[])
{
Scanner sc = new Scanner(System.in);
System.out.println("Enter the size of the array");
int n = sc.nextInt();
int[] a = new int[n];
System.out.println("Enter the elements of the sorted array");
for(int i=0; i<n; i++)
{
a[i] = sc.nextInt();
}
System.out.println("Enter the element to be searched");
int m = sc.nextInt();
int pos =-1;
int size = (int) Math.sqrt(n);
int jump = size;
/*Iterate till the array ends */
while(jump < n)
{
if(a[jump] == m)
{
pos = jump;
break;
}
else if(a[jump] < m)
{
jump = jump + size;
}
else
{
/*If element at jump position becomes larger jump back once and then perform linear search between the two jump positions. */
for(int i=jump-size; i<jump; i++)
{
if(a[i]==m)
{
pos = i;
break;
}
}
}
}
if(pos == -1)
{
System.out.println("Element not found");
}
else
{
pos = pos + 1;
System.out.println("Element found at " + pos + " position");
}
sc.close();
}
}