# Binary Search in Java

(Last Updated On: 10/10/2023)

In the age of computer science and data manipulation, efficient searching algorithms are like hidden treasures. One such gem is the Binary Search algorithm. In this blog, we will explore Binary Search in Java, covering different implementation methods and scenarios where it shines. So, let’s understand the Concept of Binary Search.

## What is a Binary Search?

Binary Search is a searching algorithm used to efficiently locate a specific element within a sorted dataset. It works by repeatedly dividing the search space in half and eliminating half of the remaining elements with each iteration. This process continues until the desired element is found or it’s determined that the element is not in the dataset.

### Binary Search with an example:

For Example, Imagine you have a sorted list of numbers, such as [1, 3, 5, 7, 9, 11, 13, 15], and you want to find the number 7 within this list.

Binary Search Steps:

1. Initial Search Space: The search begins with the entire list.

– List: [1, 3, 5, 7, 9, 11, 13, 15]

– Search Space: [1, 3, 5, 7, 9, 11, 13, 15]

2. Middle Element: Calculate the middle element of the search space.

– Middle Element: 9 (at index 4)

3. Comparison: Compare the middle element (9) with the target element (7).

– 9 is greater than 7.

4. New Search Space: Since 9 is greater than 7, we can eliminate the right half of the search space because the target (7) must be on the left side.

– New Search Space: [1, 3, 5, 7]

5. Repeat: Repeat the process with the new search space.

– Middle Element: 5 (at index 2)

– 5 is less than 7.

6. New Search Space: Since 5 is less than 7, we eliminate the left half of the search space.

– New Search Space: 

7. Repeat: Repeat the process with the new search space.

– Middle Element: 7 (at index 0)

– 7 is equal to 7.

Dive into Linear Search in Java Now!

8. Element Found: We’ve found the target element (7) at index 0.

Result: The Binary Search successfully located the number 7 in the sorted list at index 0.

## Methods of Finding Using Binary Search

Let’s take a look at three common methods of implementing binary search in Java:

1. Using the iterative approach

2. Recursive binary search

3. Using Arrays.binarySearch () method

### Using the iterative approach

Java program presents the Binary Search algorithm to efficiently find a key element in a sorted array.

```// Binary Search in Java
import java.util.*;
public class BinarySearchEx{
public static void main(String args[]){
int numArray[] = {1,7,6,5,3,4,9};
System.out.println("The input array: " + Arrays.toString(numArray));
//key to be searched
int key = 9;
System.out.println("\nKey to be searched=" + key);
//set first to first index
int first = 0;
//set last to last elements in array
int last=numArray.length-1;
//calculate mid of the array
int mid = (first + last)/2;
//while first and last do not overlap
while( first <= last ){
//if the mid < key, then key to be searched is in the first half of array
if ( numArray[mid] < key ){
first = mid + 1;
}else if ( numArray[mid] == key ){
//if key = element at mid, then print the location
System.out.println("Element is found at index: " + mid);
break;
}else{
//the key is to be searched in the second half of the array
last = mid - 1;
}
mid = (first + last)/2;
}
//if first and last overlap, then key is not present in the array
if ( first > last ){
}
}
}  ```

Explanation of the code:

1. The input array `numArray` is initialized with integer values, and the key to be searched is set to `9`.

2. Variables `first` and `last` are used to represent the indices at the beginning and end of the array, respectively. The `mid` variable is calculated as the average of `first` and `last`.

3. The program enters a `while` loop that continues as long as `first` is less than or equal to `last`.

4. Inside the loop, it checks if the element at the `mid` index is less than the `key`. If so, it updates `first` to `mid + 1`, effectively searching in the first half of the array.

5. If the element at `mid` is equal to the `key`, it prints the index where the element is found and breaks out of the loop.

6. If neither of the above conditions is met, it means the `key` should be in the second half of the array, so `last` is updated to `mid – 1`.

7. The `mid` is recalculated in each iteration.

Explore the Difference Between Compiler and Interpreter Here!

8. If the loop exits without finding the key (when `first` becomes greater than `last`), it prints a message indicating that the element is not found in the array.

This binary search algorithm efficiently narrows down the search space with each iteration, making it ideal for sorted arrays and significantly faster than linear search for larger datasets.

Pros:

– Simple and easy to understand.

– Memory-efficient as it uses a single variable (`mid`) to track the middle element.

Cons:

– Requires more code than the recursive approach.

#### Output:

``````The input array: [1, 7, 6, 5, 3, 4, 9]
Key to be searched=9
Element is found at index: 6``````

### Recursive binary search

Java program showcases the Binary Search algorithm using a recursive approach to efficiently find a key element in an array.

```// Binary Search in Java
import java.util.*;
public class BinarySearchEx{
//recursive method for binary search
public static int binarySearch(int intArray[], int low, int high, int key){
//if array is in order then perform binary search on the array
if (high>=low){
//calculate mid
int mid = low + (high - low)/2;
//if key =intArray[mid] return mid
if (intArray[mid] == key){
return mid;
}
//if intArray[mid] > key then key is in left half of array
if (intArray[mid] > key){
return binarySearch(intArray, low, mid-1, key);//recursively search for key
}else       //key is in right half of the array
{
return binarySearch(intArray, mid+1, high, key);//recursively search for key
}
}
return -1;
}
public static void main(String args[]){
//define array and key
int intArray[] = {9,8,7,6,5,4,3,2,1};
System.out.println("Input List: " + Arrays.toString(intArray));
int key = 5;
System.out.println("\nThe key to be searched:" + key);
int high=intArray.length-1;
//call binary search method
int result = binarySearch(intArray,0,high,key);
//print the result
if (result == -1)
else
System.out.println("\nKey is found at location: "+result );
}
}

```

Explanation of the code:

1. An input array `intArray` is initialized with integer values, and the key to be searched is set to `5`.

2. The `binarySearch` method takes the array, the lowest and highest indices, and the key as parameters. It recursively performs binary search.

3. Inside the method, it checks if the `high` index is greater than or equal to the `low` index, indicating a valid search range.

4. It calculates the `mid` index as the average of `low` and `high`.

5. If the element at `mid` is equal to the `key`, it returns `mid` as the result.

6. If the element at `mid` is greater than the `key`, it recursively searches the left half of the array. Otherwise, it searches the right half.

7. The program calls the `binarySearch` method and prints the result, indicating whether the key is found in the array and at which location.

This recursive binary search algorithm efficiently reduces the search space, making it highly effective for sorted arrays.

#### Output:

``````Input List: [9, 8, 7, 6, 5, 4, 3, 2, 1]
The key to be searched:5
Key is found at location: 4``````

Pros:

– Concise and expressive code.

Cons:

– May consume more memory due to recursive function calls.

### Using Arrays.binarySearch () method

Java program demonstrates how to perform a Binary Search using the `Arrays.binarySearch()` method, which is a built-in feature for arrays.

```// Binary Search in Java
import java.util.Arrays;
class BinarySearchEx{
public static void main(String args[]){
//define an array
int intArray[] = {1,2,3,4,5,6,7,8,9};
System.out.println("The input Array : " + Arrays.toString(intArray));
//define the key to be searched
int key = 5;
System.out.println("\nThe key to be searched:" + key);
//call binarySearch method on the given array with key to be searched
int result = Arrays.binarySearch(intArray,key);
if (result < 0)
else
System.out.println("\nKey is found at index: "+result);
}
}```

Explanation of the code:

1. An input array `intArray` is initialized with sorted integer values, and the key to be searched is set to `5`.

2. The program displays the input array using `Arrays.toString()` for clarity.

3. It calls the `Arrays.binarySearch()` method on the input array with the key to be searched.

4. If the result is less than 0, it means the key is not found in the array, and a corresponding message is printed.

5. If the result is non-negative, it indicates that the key is found at the returned index, and the index is displayed as the result.

This approach leverages the built-in Java functionality to perform binary search efficiently on sorted arrays.

#### Output:

``````The input Array : [1, 2, 3, 4, 5, 6, 7, 8, 9]
The key to be searched:5
Key is found at index: 4 in the array.``````

Pros:

– Simplicity and convenience for performing binary search on sorted arrays.

Cons:

– It returns a negative value if the element is not found, which requires additional handling and may not provide the exact location of insertion.

## Use Cases and Applications of Binary Search in Java

Binary search finds applications in scenarios where quick and efficient searching is vital. These include :

1. Searching in Databases: Binary search is widely used in database systems to quickly locate records based on indexed columns, reducing query execution time.

2. Sorting Algorithms: Binary search plays a crucial role in sorting algorithms like QuickSort and MergeSort, which rely on efficient searching within subarrays.

3. File Systems: It is employed in file systems to search for files or directories within a directory tree efficiently.

4. Game Development: Binary search can be used in game development to optimize collision detection algorithms or find specific game elements within large datasets.

5. Web Development: In web development, binary search can be utilized for optimizing search algorithms on sorted lists or arrays of data.

6. Telecommunications: Binary search is used in telecommunication networks to quickly locate information in databases, such as finding a subscriber’s information.

7. Mathematical Calculations: It is applied in mathematical calculations, like finding roots of equations using methods such as the bisection method.

8. Scientific Research: Binary search can be used in various scientific research applications, including data analysis and simulations.

9. Geospatial Data: Geospatial applications use binary search to efficiently search for locations or coordinates within spatial databases.

10. Automated Trading: In financial markets, binary search can be employed to search for specific trading data or patterns in historical data.

These examples demonstrate the versatility of binary search in various domains, where efficient searching or sorting is essential for optimal performance.

## Best Practices and Tips for Using Binary Search in Java

To learn tips and best practices for Using Binary Search in Java. To make the most of binary search, Check out a few following tips:

1. Sorted Data: Ensure that the input data is sorted in ascending order before applying binary search. Binary search only works on sorted arrays or lists.

2. Check for Empty Data: Always check if the array or list is empty before performing binary search to avoid runtime errors.

3. Use Built-in Functions: If possible, leverage built-in functions like `Arrays.binarySearch()` for simplicity and efficiency.

4. Correct Indices: Pay close attention to the indices used in binary search, including `first`, `last`, and `mid`, to prevent off-by-one errors.

5. Update Boundaries: In each iteration, update the search boundaries (`first` and `last`) correctly based on the comparison between the middle element and the target value.

7. Testing: Thoroughly test the binary search algorithm with various input scenarios, including edge cases, to ensure correctness and efficiency.

8. Consider Alternatives: For small datasets or unsorted data, consider alternative search algorithms like linear search, which might be simpler and equally efficient.

9. Optimize Data Structures: In certain scenarios, consider using more efficient data structures like binary search trees (BST) if the data frequently changes.

10. Documentation: Document your binary search code with clear comments and explanations for future reference and collaboration.

By following these best practices, you can effectively utilize binary search in your Java programs, ensuring both accuracy and efficiency in your searching algorithms.

Binary Search in Java is a powerful technique for finding elements efficiently in sorted collections. Its speed and effectiveness make it a valuable tool for various applications. By mastering binary search, you can significantly enhance your programming and problem-solving skills.

With this blog, you’re now clear with the knowledge to implement binary search in Java.  For more information on Java programming, please visit our Newtum website. We offer a variety of courses and blogs that can help you learn Java and other programming languages from beginner to advanced levels. Happy coding with Newtum!

## FAQ for Binary Search in Java

1. What is binary search, and how does it work in Java?

– Binary search is a searching algorithm used to find a specific element in a sorted array or list by repeatedly dividing the search space in half. In Java, it’s implemented using iterative or recursive approaches.

2. What are some real-world applications of binary search in Java?

– Binary search is used in databases, file systems, game development, web development, mathematical calculations, and various scientific research applications.

3. When should I use binary search over linear search in Java?

– Use binary search when dealing with large, sorted datasets where efficiency is critical. For smaller or unsorted data, linear search may be simpler and equally efficient.

4. How do I avoid common pitfalls and errors when implementing binary search in Java?

– To avoid errors, ensure that your data is sorted, handle edge cases, and update search boundaries correctly in each iteration. Thoroughly test your binary search algorithm.

5. What are some real-world applications of binary search in Java?

– Binary search is used in databases, file systems, game development, web development, mathematical calculations, and various scientific research applications.