-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBinarySearch.java
More file actions
35 lines (31 loc) · 860 Bytes
/
BinarySearch.java
File metadata and controls
35 lines (31 loc) · 860 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
//Binary Search Implementation
public class BinarySearch{
//Returns the index of the searched item in the array. If not, returns -1.
public int search(int arr[],int item) {
int N = arr.length;
int lo=0,hi=N-1;
while(lo<=hi) {
int mid = lo + (hi-lo)/2;
if(arr[mid] == item) {
return mid;
}
else if(item > arr[mid]) {
lo = mid+1;
}
else if(item < arr[mid]) {
hi = mid-1;
}
}
return -1;
}
public static void main(String[] args) {
BinarySearch bs = new BinarySearch();
int[] arr = {0, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30, 32, 34, 36, 38};
int item = 6;
int result = bs.search(arr, item);
if(result==-1) {
System.out.println("The item is not present in the array!");
}
else System.out.println("The item is found at index " +result);
}
}