-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSearch.java
More file actions
52 lines (45 loc) · 1.61 KB
/
Copy pathSearch.java
File metadata and controls
52 lines (45 loc) · 1.61 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
public class Search {
public static int linear_search (int numbers[],int key){
for(int i=0;i<=numbers.length;i++){
if (numbers[i]==key) {
return i;
}
}
return -1;
}
public static int binary_search(int numbers[],int key){
int start = 0;
int end = numbers.length-1;
while(start<=end) {
int mid = (start + end)/2;
if(numbers[mid]==key){
return mid;
}
else if(numbers[mid]>key){
end = mid-1;
}
else{
start=mid+1;
}
}
return -1;
}
public static void main(String[] args) {
int numbers[]={2,4,6,8,10};
int key = 10;
int index = linear_search(numbers, key);
if (index == -1) {
System.out.println(" Key is not found ");
}
else{
System.out.println(" Key found at " + index);
}
int indx = binary_search(numbers, key);
if (index == -1) {
System.out.println(" Key is not found ");
}
else{
System.out.println(" Key found at " + index);
}
}
}