-
Notifications
You must be signed in to change notification settings - Fork 0
/
BinarySearch.java
42 lines (38 loc) · 1.15 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
import java.util.Scanner;
public class BinarySearch {
public static int binarySearch(int arr[], int low, int high, int key) {
int mid = (low + high) / 2;
while (low <= high) {
if (arr[mid] < key) {
low = mid + 1;
} else if (arr[mid] == key) {
return mid;
} else {
high = mid - 1;
}
mid = (low + high) / 2;
}
if (low > high) {
return -1;
}
return 1;
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter the Size of array: ");
int x = sc.nextInt();
int ar[] = new int[x];
for(int i =0;i<x;i++){
System.out.print("Enter Element: ");
ar[i] =sc.nextInt();
}
System.out.println("Enter the String to be found: ");
int key = sc.nextInt();
if(binarySearch(ar, 0, x, key)==-1){
System.out.println("Key is not found..!!");
}else{
System.out.println("Key found found..!!");
}
sc.close();
}
}