-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathbinarysearch.java
More file actions
66 lines (53 loc) · 1.77 KB
/
binarysearch.java
File metadata and controls
66 lines (53 loc) · 1.77 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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
package daaa;
import java.util.Scanner;
import java.util.Arrays;
public class binarysearch {
// Method to perform binary search
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;
// Check if the target is at mid
if (arr[mid] == target) {
return mid;
}
// If target is smaller, ignore right half
if (arr[mid] > target) {
right = mid - 1;
}
// If target is greater, ignore left half
else {
left = mid + 1;
}
}
return -1; // Element not found
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
// Input array size
System.out.print("Enter the number of elements: ");
int size = sc.nextInt();
int[] arr = new int[size];
// Input array elements
System.out.println("Enter " + size + " elements:");
for (int i = 0; i < size; i++) {
arr[i] = sc.nextInt();
}
// Sort the array (binary search requires sorted array)
Arrays.sort(arr);
System.out.println("Sorted Array: " + Arrays.toString(arr));
// Input target element to search
System.out.print("Enter the element to search: ");
int target = sc.nextInt();
// Perform binary search
int result = binarySearch(arr, target);
// Output result
if (result == -1) {
System.out.println("Element not found.");
} else {
System.out.println("Element found at index: " + result);
}
sc.close();
}
}