forked from HarshCasper/NeoAlgo
-
Notifications
You must be signed in to change notification settings - Fork 0
/
jumpSearch.java
61 lines (56 loc) · 3.37 KB
/
jumpSearch.java
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
import java.util.*;
public class Main
{
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
int indexI,indexJ,searchElement,countsToJump,lengthOfArray,position;
System.out.println("Enter number of elements in array");
lengthOfArray=sc.nextInt();
int array[]=new int[lengthOfArray];
System.out.println("Enter array elements");
for(indexI=0;indexI<lengthOfArray;indexI++)
array[indexI]=sc.nextInt();
System.out.println("Enter element to be searched");
searchElement=sc.nextInt();
countsToJump=(int)Math.sqrt(lengthOfArray);
position=-1;indexI=0;
while(indexI<lengthOfArray)
{
if(array[indexI]==searchElement)
position=indexI;
if(array[indexI]>searchElement)
break;
indexI=indexI+countsToJump;
}
indexJ=0;
while(indexJ<countsToJump)
{
indexI--;
indexJ++;
if(array[indexI]==searchElement)
{position=indexI;
break;
}
}
if(position==-1)
System.out.println("Element not found");
else
System.out.println("Element found at "+position);
}
}
/* Enter number of elements in array
10
Enter array elements
1
2
3
4
5
6
7
8
9
10
Enter element to be searched
5
Element found at 4 */