-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBinarySearch.java
More file actions
47 lines (36 loc) · 1.37 KB
/
BinarySearch.java
File metadata and controls
47 lines (36 loc) · 1.37 KB
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
41
42
43
44
45
46
47
import java.util.Arrays;
public class BinarySearch {
// Binary search method to find a target value in a sorted array
public static int binarySearch(int[] array, int target) {
int left = 0;
int right = array.length - 1;
while (left <= right) {
int mid = left + (right - left) / 2;
if (array[mid] == target) {
return mid; // Found target, return index
}
if (array[mid] < target) {
left = mid + 1; // Search right half
} else {
right = mid - 1; // Search left half
}
}
return -1; // Target not found
}
// Sorting method to sort the array before applying binary search
public static void sortArray(int[] array) {
Arrays.sort(array); // Using built-in sorting method
}
public static void main(String[] args) {
int[] array = {10, 5, 8, 3, 7, 6};
sortArray(array); // First, sort the array
System.out.println("Sorted Array: " + Arrays.toString(array));
int target = 7;
int result = binarySearch(array, target);
if (result != -1) {
System.out.println("Element found at index: " + result);
} else {
System.out.println("Element not found.");
}
}
}