This post will discuss how to search for a given target value in a sorted array of integers using binary search implementation provided by the C++ standard library (STL) and Java Collection framework.

1. Binary Search in STL

In C++, STL library has std::binary_search function defined in the header “algorithm”. It takes the iterators to the starting and ending positions of a sorted sequence and returns true if the target value is found; otherwise, returns false. This search operation takes O(log(n)) time and is very efficient even for large sorted arrays.

The following C++ program demonstrates its usage on a sorted integer array:

Download  Run Code

Output:

Element is found at index 3

2. Binary Search in Java Collections

In Java, we can use the binarySearch() method provided by the Arrays class. It searches the specified sorted array (or the range of it) for the target value using the binary search algorithm. It is overloaded for all primitive types and can also sort an object array using a comparator.

Unlike std::binary_search, which returns true on success, Arrays.binarySearch() returns the search key index if it is contained in the array; otherwise, a negative value is returned. If a sorted array is not passed to it, the results are undefined.

The following Java program demonstrates its usage on a sorted integer array:

Download  Run Code

Output:

Element is found at index 3

 
You can also implement the binary search algorithm, as discussed in detail in the following post:

Binary Search Algorithm – Iterative and Recursive Implementation