-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBS.java
More file actions
40 lines (30 loc) · 977 Bytes
/
BS.java
File metadata and controls
40 lines (30 loc) · 977 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
36
37
38
39
40
import java.util.Arrays;
public class BS {
public static void main(String[] args) {
int arr[] = {4,26,1,3,87,20 };
Arrays.sort(arr);
System.out.println("Sorted Array: " + Arrays.toString(arr));
int target = 26;
int result = binary_search(arr, target);
if (result != -1) {
System.out.println("Find the Element! , at index of : " + result);
} else {
System.out.println("Not found the Element ");
}
}
static int binary_search(int arr[], int target) {
int leftIndex = 0;
int rightIndex = arr.length - 1;
while (leftIndex <= rightIndex) {
int mid = (leftIndex + rightIndex) / 2;
if (arr[mid] == target) {
return mid;
} else if (arr[mid] > target) {
rightIndex = mid - 1;
} else {
leftIndex = mid + 1;
}
}
return -1;
}
}