-
Notifications
You must be signed in to change notification settings - Fork 0
/
BINARY_SEARCH
39 lines (38 loc) · 1.16 KB
/
BINARY_SEARCH
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
//program that take an array input from user and finding key using Binary Search.
import java.util.*;
public class BINARY_SEARCH {
public static int BinarySEARCH(int arr[], int key){
int start = 0;
int end = arr.length - 1;
while(start<=end){
int mid = (start+end)/2;
if(arr[mid]==key){
return mid;
}
if(arr[mid] < key){
start = mid+1;
} else {
end = mid-1;
}
}
return -1;
}
public static void main(String args[]){
Scanner sc = new Scanner(System.in);
System.out.print("Enter a value : ");
int n = sc.nextInt();
int arr[] = new int[n];
System.out.println("Enter array element : ");
for(int i=0; i<arr.length; i++){
arr[i] = sc.nextInt();
}
System.err.print("Enter key value : ");
int key = sc.nextInt();
int index = BinarySEARCH(arr, key);
if(index == -1){
System.out.println("Key not found.");
} else {
System.out.println(key+" found at "+index+"th index.");
}
}
}