-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBinarysearch.java
More file actions
35 lines (34 loc) · 1009 Bytes
/
Binarysearch.java
File metadata and controls
35 lines (34 loc) · 1009 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
public class Binarysearch {
public static int binarysearch(int arr[] , int search_element) {
int left = 0;
int right = arr.length -1;
int step=0;
while(left <= right) {
step++;
int mid = (left+right)/2;
if (arr[mid] == search_element ) {
System.out.println(step);
return mid;
}
else if(arr[mid] > search_element ) {
right = mid-1;
}
else{
left = mid+1;
}
}
System.out.println(step);
return -1;
}
public static void main(String[] args) {
int num[] = {3,5,6,7,8,9,33,54};
int item = 54;
int index = binarysearch(num,item);
if (index != -1) {
System.out.println("tne location of element is"+index);
}
else{
System.out.println("Element not found");
}
}
}