-
Notifications
You must be signed in to change notification settings - Fork 29
/
Binary_Search.java
41 lines (35 loc) · 907 Bytes
/
Binary_Search.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
/*
In binary search we split the array by finding it's
midpoint and the search is comparitively faster than
linear search
*/
import java.util.Scanner;
public class Binary_Search {
public static int binary(int arr[],int si,int ei,int d){
int a = -1;
if(si>ei){
return -1;
}
int mid = (si+ei)/2;
if(arr[mid]==d){
return mid;
}
if(mid==arr.length-1){
return a;
}
if(arr[mid]<d){
a = binary(arr,mid+1,ei,d);
}
else {
a = binary(arr,si,mid-1,d);
}
return a;
}
public static void main(String[] args) {
int arr[] = {1,2,3,4,5};
Scanner s = new Scanner(System.in);
System.out.println("Enter no. to be searched");
int d = s.nextInt();
System.out.println(binary(arr,0,arr.length-1,d));
}
}