forked from jainaman224/Algo_Ds_Notes
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Binary_Search.java
60 lines (51 loc) · 1.16 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
54
55
56
57
58
59
60
import java.util.Scanner;
class Binary_Search
{
// Function for binary search
public static int binarySearch(int[] array, int size, int desired)
{
int left = 0, right = size - 1, middle;
while (left <= right)
{
middle = left + (right - left) / 2;
if (array[middle] == desired)
return middle;
else if (desired < array[middle])
right = middle - 1;
else
left = middle + 1;
}
return -1;
}
// Driver Function
public static void main(String[] args)
{
int num;
Scanner s = new Scanner(System.in);
num = s.nextInt();
int array[] = new int[num];
for (int i = 0; i < num; i++) {
array[i] = s.nextInt();
}
int desired;
desired = s.nextInt();
if (binarySearch(array, num, desired) != -1)
System.out.println("Found");
else
System.out.println("Not Found");
}
}
/*
Input:
num = 7
array = {1, 2, 3, 4, 5, 6, 7}
desired = 4
Output:
Found
Input:
num = 5
array = {1, 3, 5, 7, 9}
desired = 2
Output:
Not Found
*/