forked from 790hanu/Annex-qr-code-simulator
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Binary Search.java
53 lines (34 loc) · 1.07 KB
/
Binary Search.java
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
import java.util.Scanner;
class Main {
int binarySearch(int array[], int element, int low, int high) {
while (low <= high) {
int mid = low + (high - low) / 2;
if (array[mid] == element)
return mid;
if (array[mid] < element)
low = mid + 1;
else
high = mid - 1;
}
return -1;
}
public static void main(String args[]) {
Main obj = new Main();
// create a sorted array
int[] array = { 3, 4, 5, 6, 7, 8, 9 };
int n = array.length;
// get input from user for element to be searched
Scanner input = new Scanner(System.in);
System.out.println("Enter element to be searched:");
// element to be searched
int element = input.nextInt();
input.close();
// call the binary search method
// pass arguments: array, element, index of first and last element
int result = obj.binarySearch(array, element, 0, n - 1);
if (result == -1)
System.out.println("Not found");
else
System.out.println("Element found at index " + result);
}
}