-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbinarySearch.java
More file actions
50 lines (35 loc) · 958 Bytes
/
Copy pathbinarySearch.java
File metadata and controls
50 lines (35 loc) · 958 Bytes
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
package Arrays;
import java.util.Scanner;
public class binarySearch {
static int binary_search(int arr[],int n,int key){
//Implement binary search
int s = 0;
int e = n - 1;
while(s<=e){
int mid = (s+e)/2;
if(arr[mid] == key){
return mid;
}
else if(arr[mid] > key){
e = mid - 1;
}
else{
s = mid + 1;
}
}
return -1;
}
public static void main(String[] args){
int arr[] = {10,20,30,40,45,60,70,89};
int n = arr.length;
Scanner scn = new Scanner(System.in);
int key = scn.nextInt();
int index = binary_search(arr,n,key);
if(index!=-1){
System.out.println(key + " is present at index " + index);
}
else{
System.out.println(key + " is NOT Found!");
}
}
}