-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBinarySearch.java
More file actions
41 lines (35 loc) · 1.12 KB
/
BinarySearch.java
File metadata and controls
41 lines (35 loc) · 1.12 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
import java.util.Scanner;
public class BinarySearch {
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;
if (arr[mid] < target)
left = mid + 1;
else
right = mid - 1;
}
return -1;
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter the size of array");
int size = sc.nextInt();
int[] arr = new int[size];
System.out.println("Enter array Element");
for(int i=0;i<size;i++){
arr[i]=sc.nextInt();
}
System.out.println("Enter the element to find");
int target=sc.nextInt();
int result = binarySearch(arr, target);
if (result == -1)
System.out.println("Element not present");
else
System.out.println("Element found at index " + result);
sc.close();
}
}