forked from Dua2022/javaByDua
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathA.java
33 lines (30 loc) · 879 Bytes
/
A.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
package preparation;
public class A {
static int Binary_search(int arr[], int l,int r,int x){
while (r>=l){
int mid = l+(r-1)/2;
if (arr[mid]==x){
System.out.println("element found");
return mid;
}
if (arr[mid]<x){
return Binary_search(arr,l,mid-1,x);
}
else {
return Binary_search(arr,mid+1,r,x);
}
}
return -1;
}
public static void main(String[] args) {
int arr[]= {1,6,2,4,8,9,3};
int x = 4;
int result = Binary_search(arr,0, arr.length-1,x);
if (result == -1){
System.out.println("element not found");
}
else {
System.out.println("element found at index "+result);
}
}
}