# Binary Search Java Program

Binary search, also known as half-interval search,binary chop or logarithmic search.

## How it Works?

Binary search works on sorted arrays values. Binary search begins by comparing the middle element of the array with the target value. If the target value matches the middle element, its position in the array is returned. If the target value is less than or greater
than the middle element, the search continues in the lower or upper half of the array, respectively, eliminating the other half from consideration.If the search ends with the remaining half being empty, the target is not in the array.

## Time and Space Complexity?

Binary search runs in at worst logarithmic time, making O(log n) comparisons and takes constant (O(1)) space.

where n is the number of elements in the array, the O is Big O notation, and log is the logarithm.

## Java API  for Binary Search

Java Arrays class also provide api’s for Binary Search. You can use as below

```import java.util.Arrays;

public class BinarySearchByJavaAPI {

public static void main(String[] args) {
char characters[] = { 'l', 'm', 'n', 'p', 'q&lt;span 				data-mce-type=&quot;bookmark&quot; 				id=&quot;mce_SELREST_start&quot; 				data-mce-style=&quot;overflow:hidden;line-height:0&quot; 				style=&quot;overflow:hidden;line-height:0&quot; 			&gt;&lt;/span&gt;' };

System.out.println(Arrays.binarySearch(characters, 'a'));
System.out.println(Arrays.binarySearch(characters, 'p'));

}

}
```

## Java Program for Binary Search

```import java.util.Scanner;

class BinarySearch
{
public static void main(String args[])
{
int c, first, last, middle, n, search, array[];

Scanner in = new Scanner(System.in);
System.out.println(&quot;Enter number of elements&quot;);
n = in.nextInt();
array = new int[n];

System.out.println(&quot;Enter &quot; + n + &quot; sorted integers&quot;);

for (c = 0; c &lt; n; c++)
array = in.nextInt();

System.out.println(&quot;Enter value to find&quot;);
search = in.nextInt();

first  = 0;
last   = n - 1;
middle = (first + last)/2;

while( first &lt;= last )
{
if ( array[middle] &lt; search )                 first = middle + 1;                else if ( array[middle] == search )     {                System.out.println(search + &quot; found at location &quot; + (middle + 1) + &quot;.&quot;);                break;        }        else                last = middle - 1;           middle = (first + last)/2;     }     if ( first &gt;&lt;span 				data-mce-type=&quot;bookmark&quot; 				id=&quot;mce_SELREST_start&quot; 				data-mce-style=&quot;overflow:hidden;line-height:0&quot; 				style=&quot;overflow:hidden;line-height:0&quot; 			&gt;&lt;/span&gt; last )
System.out.println(search + &quot; is not present in the list.\n&quot;);
}
}
```