-
Notifications
You must be signed in to change notification settings - Fork 14
Expand file tree
/
Copy pathbinarySearch.java
More file actions
30 lines (26 loc) · 1012 Bytes
/
binarySearch.java
File metadata and controls
30 lines (26 loc) · 1012 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
public class BinarySeach {
public static int binarySearch(int array[], int target) {
int start = 0;
int end = array.length-1;
while(start<=end) {
int mid = Math.round(start+end)/2;
if(array[mid] == target ) {
return mid;
} else if(array[mid]< target) {
start= mid+1;
} else {
end = mid-1;
}
}
return -1;
}
public static void main(String[] args) {
int array[] = {18,19,23,45,67,89,98,102,123,456};
int index = binarySearch(array, 123);
if(index==-1) {
System.out.println("Element not found");
} else {
System.out.println("Element found: " + index);
}
}
}