-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathJump_Search.java
More file actions
71 lines (54 loc) · 1.36 KB
/
Jump_Search.java
File metadata and controls
71 lines (54 loc) · 1.36 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
64
65
66
67
68
69
70
71
/*
* Array must be sorted
* time complexity:O(sqrt(n))
* space complexity O(1)
* first jump is performed then linear search,
* */
package java_ds_algo;
import java.util.Scanner;
import java.lang.Math;
public class Jump_Search {
//this is leanear search returns position
public static int linearSearch(int[] arr,int r,int s,int x) {
int pos = 0;
for(int i = s;i<i+s;i++) {
if(arr[i] == x) {
pos = i;
break;
}
}
return pos+1;
}
//jump search is performed to know range
public static int jumpSearch(int[] arr ,int n,int s,int x) {
int pos = -1;
for(int i =0;i < n;i= i+s) {
if(arr[i] > x) {
pos = i;
break;
}
}
return pos;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner sc = new Scanner(System.in);
System.out.println("Enter length of array");
int n = sc.nextInt();
int[] arr = new int[n];//array
System.out.println("Enter Element to be sorted through Jump Search in a new line");
for(int i = 0;i < n;i++) {
arr[i] = sc.nextInt();
}
System.out.println("Enter element to be searched in a new line");
int x = sc.nextInt();
int s = (int)Math.floor(Math.sqrt(n));
int r = jumpSearch(arr,n,x,s);
if(r != -1) {
System.out.println("position is :"+linearSearch(arr,r,s,x));
}
else {
System.out.println("Number is not in array");
}
}
}