-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy pathbinary_search.java
More file actions
32 lines (23 loc) · 788 Bytes
/
binary_search.java
File metadata and controls
32 lines (23 loc) · 788 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
import java.util.Arrays;
public class binary_search {
public static void main(String[] args) {
int arr[] = { 1, 2, 4, 5, 6 };
Arrays.sort(arr);
int search = 2;
int ans = binary_search(0, (arr.length - 1), arr, search);
System.out.println(ans);
}
static int binary_search(int low, int high, int arr[], int search) {
if (low <= high) {
int mid = (high + low) / 2;
if (search == arr[mid]) {
return mid;
} else if (search > arr[mid]) {
return binary_search(mid + 1, high, arr, search);
} else {
return binary_search(low, mid - 1, arr, search);
}
}
return -1;
}
}