-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathProgram12.java
More file actions
43 lines (33 loc) · 1.02 KB
/
Copy pathProgram12.java
File metadata and controls
43 lines (33 loc) · 1.02 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
import java.util.Scanner;
public class Program12 {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Enter size of array");
int n = scanner.nextInt();
int[] arr = new int[n];
System.out.println("Enter array");
for (int i = 0; i < n; i++) {
arr[i] = scanner.nextInt();
}
System.out.println("Enter element to search");
int search = scanner.nextInt();
// Binary Search
int low = 0;
int high = n -1;
int index = -1;
while (low <= high) {
int mid = low + (high - low) / 2;
if (arr[mid] == search)
index = mid;
if (arr[mid] < search)
low = mid + 1;
else
high = mid - 1;
}
if (index == -1) {
System.out.println("Element not found");
} else {
System.out.println("Element is at index: " + index);
}
}
}