-
Notifications
You must be signed in to change notification settings - Fork 28
/
Copy pathAmann
37 lines (29 loc) · 1.05 KB
/
Amann
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
public class BinarySearch {
// Function to perform binary search on a sorted array
public static int binarySearch(int[] arr, int target) {
int left = 0;
int right = arr.length - 1;
while (left <= right) {
int mid = left + (right - left) / 2;
if (arr[mid] == target) {
return mid; // Element found, return its index
}
if (arr[mid] < target) {
left = mid + 1; // Search the right half
} else {
right = mid - 1; // Search the left half
}
}
return -1; // Element not found
}
public static void main(String[] args) {
int[] sortedArray = {2, 4, 6, 8, 10, 12, 14, 16, 18, 20};
int target = 12;
int result = binarySearch(sortedArray, target);
if (result != -1) {
System.out.println("Element " + target + " found at index " + result);
} else {
System.out.println("Element " + target + " not found in the array.");
}
}
}