-
Notifications
You must be signed in to change notification settings - Fork 11
Expand file tree
/
Copy pathBinarySearch.java
More file actions
74 lines (69 loc) · 2.49 KB
/
Copy pathBinarySearch.java
File metadata and controls
74 lines (69 loc) · 2.49 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
67
68
69
70
71
72
73
74
package searchingAndSorting;
import java.util.Scanner;
/*You have been given a sorted(in ascending order) integer array/list(ARR) of size N and an element X. Write a function to search this element in the given input array/list using 'Binary Search'. Return the index of the element in the input array/list. In case the element is not present in the array/list, then return -1.
Input format:
The first line contains an Integer 'N' which denotes the size of the array/list.
Second line contains 'N' single space separated integers representing the elements in the array/list.
Third line contains an Integer 't' which denotes the number of test cases or queries to be run. Then the test cases follow..
All the 't' lines henceforth, will take the value of X to be searched for in the array/list.
Output Format:
For each test case, print the index at which X is present, -1 otherwise.
Output for every test case will be printed in a separate line.
Constraints:
1 <= t <= 10^4
0 <= N <= 10^6
0 <= X <= 10^9
Time Limit: 1 sec
Sample Input 1:
7
1 3 7 9 11 12 45
1
3
Sample Output 1:
1
Sample Input 2:
7
1 2 3 4 5 6 7
2
9
7
Sample Output 2:
-1
6*/
public class BinarySearch {
public static int binarySearch(int[] arr, int searchQuery) {
int start = 0;
int end = arr.length - 1;
int midElement;
while (start <= end) {
midElement = start + (end - start) / 2;
if (arr[midElement] > searchQuery) {
end = midElement - 1;/*If middle element is more than x, we’ll do the search in the left half of the array.*/
} else if (arr[midElement] < searchQuery) {
start = midElement + 1;/*If middle element is less than x, we’ll do the search in the right half of the array.*/
} else {
return midElement; /*If middle element is equal to x, return that element’s index.*/
}
}
return -1;
}
public static int[] takeArrayInput() {
Scanner scan = new Scanner(System.in);
int size = scan.nextInt();
int[] arr = new int[size];
for (int i = 0; i < size; i++) {
arr[i] = scan.nextInt();
}
return arr;
}
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int[] arr = takeArrayInput();
int testCases = scan.nextInt();
while (testCases != 0) {
int x = scan.nextInt();
System.out.println(binarySearch(arr, x));
testCases--;
}
}
}