forked from iharsh234/Algo_Ds_Notes
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Binary_Search.java
47 lines (38 loc) · 1.01 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
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[] array = {1, 2, 3, 4, 5, 6, 7};
// Element 4 to be searched
if (BinarySearch(array, 7, 4) != -1)
System.out.println("Found");
else
System.out.println("Not Found");
//Element 9 to be searched
if (BinarySearch(array, 7, 9) != -1)
System.out.println("Found");
else
System.out.println("Not Found");
}
}
/* Output
Found
Not Found
*/