-
Notifications
You must be signed in to change notification settings - Fork 3
/
BinarySearch.java
46 lines (42 loc) · 1.23 KB
/
BinarySearch.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
import java.io.*;
import java.lang.*;
import java.util.*;
public class Main
{
public static void bsearch(int arr[], int start, int end, int num)
{
int mid = start + (end-1)/2;
if(start>end)
{
System.out.println("Number Not Found");
}
else if(arr[mid]==num)
{
System.out.println("Your number found at possition : "+(mid+1));
}
else if(arr[mid]>num)
{
end = mid-1;
bsearch(arr,start,end,num);
}
else if(arr[mid]<num)
{
start = mid+1;
bsearch(arr,start,end,num);
}
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Enter the size of Array");
int n = scanner.nextInt();
int[] arr = new int[n];
System.out.println("Enter an array of " + n +" numbers in sorted form to using binary search :");
//Binary search works only on sorted arrays
for(int i=0; i<n; i++){
arr[i] = scanner.nextInt();
}
System.out.println("Enter the number you wants to search \n");
int num = scanner.nextInt();
bsearch(arr, 0, n-1, num);
}
}