In Java, binarySearch() is a method that helps in searching a particular key element from several elements using the binary search algorithm. In order to perform this operation, elements have to be sorted in ascending order. If it is not sorted, it can be sorted using the method Arrays.sort(arr). Otherwise, results are said to be undefined. Compared to linear search, binary search is considered to be faster. Due to this, the binary search’s time complexity is said to be O(log n). Moreover, the binarySearch() method can be instantiated from the package java.util.Arrays. More details on the binarySearch() method will be discussed in the following sections.
Syntax:
Start Your Free Software Development Course
Web development, programming languages, Software testing & others
public static int binarySearch(Object[] a, Object key)
Here, the parameters a and key are the array that has to be searched and the value to be found, respectively.
binarySearch() method returns the index of the key element that was searching for. In the case where the key element is not found, an insertion point where the key element that would have been inserted will be returned. If the search’s key element is not comparable to other elements in the array, an exception known as ClassCastException will be thrown.
How BinarySearch() Method Works in Java?
Let us see how this method works in Java:
- Suppose k is the key element that has to be searched for. Compare k with the array’s middle element.
- If k is matched with the element in the middle position, the mid-index has to be returned.
- Else, If k is higher than the element in the middle position, then k can be found only on the right side of the mid element.
- Otherwise, it can be found on the left side of the middle element.
Examples to Implement BinarySearch() in Java
Below are examples of some programs on the BinarySearch() method.
Example #1
Code:
import java.util.Arrays; public class BinarySearchExample { public static void main(String[] args) { //create a byte array byte ba[] = {05, 10, 15, 20, 25, 30}; //create a character array char ca[] = {'a', 'n', 's', 'p', 'v', 'i', 'd'}; //create an integer array int ia[] = { 10, 20, 15, 22, 35}; //create a double array double da[] = {10.1 , 15.34 , 22.25, 13.5}; //create a float array float fa[] = {13.2f, 25.1f , 22.2f , 43.5f }; //sort all the arrays that created above Arrays.sort(ba); Arrays.sort(ca); Arrays.sort(ia); Arrays.sort(da); Arrays.sort(fa); //enter the key elements that has to be searched in the array byte bKey = 15; char cKey = 'i'; int iKey = 22; double dKey = 15.34; float fKey = 22.2f; System.out.println("Element "+ bKey + " is found at the position of " + Arrays.binarySearch(ba,bKey) ); System.out.println("Element "+ cKey + " is found at the position of " + Arrays.binarySearch(ca,cKey) ); System.out.println("Element "+ iKey + " is found at the position of " + Arrays.binarySearch(ia,iKey) ); System.out.println("Element "+ dKey + " is found at the position of " + Arrays.binarySearch(da,dKey) ); System.out.println("Element "+ fKey + " is found at the position of " + Arrays.binarySearch(fa,fKey) ); } }
Output:
Certain arrays of different types such as character, integer, float, double, and bytes are created after sorting the arrays using Arrays in the above program.Sort() method, elements that have to be searched in the arrays are declared. Then the index of the searched element is printed using the Arrays.binarySearch() method.
Suppose a key element is given that is not present in the array; what will be the output??
In order to find that, let us change the code of key elements as shown below.
byte bKey = 15;
char cKey = ‘i’;
int iKey = 89;
double dKey = 15.34;
float fKey = 22.2f;
That is, iKey=89 is not present in the array, then the output will be displayed as below.
As we can see, the position is printed as -6. It is because if an element is searched and not found, the index’s negative value will be returned if that element was present. i.e ,int ia[] = { 10, 20, 15, 22, 35} is the given array. If 89 were present, the array would have been int ia[] = { 10, 20, 15, 22, 35, 89};
It can be clearly seen that the index would have been 6. As it is not present in the original array, that particular index’s negative value is returned in the above output.
Example #2
A binary search can also be done with the help of recursion, as shown below.
Code:
//sample class class BinarySearchExample{ public static int binarySearch(int a[], int f, int l, int k){ //if last element is greater than or equal to first element if (l>=f) { //find the mid int m = f + (l - f)/2; //if the key element that is searching is found in middle position, return mid position if (a[m] == k) { return m; } //if key element is less than element in middle position, search the left <u>subarray</u> if (a[m] > k){ return binarySearch(a, f, m-1, k); } //if key element is greater than the element in middle position, search the right <u>subarray</u> else{ return binarySearch(a, m+1, l, k); } } return -1; } public static void main(String args[]){ //initialise the array int a[] = {34,45,54,68,79}; int k = 68; int l = a.length-1; //store the position in variable res int res = binarySearch(a,0,l,k); if (res == -1) System.out.println("Sorry!! Can't find the element....!"); else System.out.println("Element is found at the position: "+res); } }
Output:
In the above program, an array is created first, and the element to be found out is also declared. Using the binarySearch() method, the position of the key elements will be found out. Suppose the element is not found, a message will be printed as “Sorry !!!Can’t find the element”.
Conclusion
binarySearch() is a Java method that helps find a particular key element among several elements available in the array using the binary search algorithm. Working and examples of this method are explained in this document in detail.
Recommended Article
This is a guide to BinarySearch() in Java. Here we discuss how the BinarySearch() Method Works in Java and examples with code implementation. You can also go through our other suggested articles to learn more –
- JavaScript Math Functions
- Layout in Java
- Java Compilers
- Merge Sort In Java
The above is the detailed content of BinarySearch() in Java. For more information, please follow other related articles on the PHP Chinese website!

Java'splatformindependencemeansdeveloperscanwritecodeonceandrunitonanydevicewithoutrecompiling.ThisisachievedthroughtheJavaVirtualMachine(JVM),whichtranslatesbytecodeintomachine-specificinstructions,allowinguniversalcompatibilityacrossplatforms.Howev

To set up the JVM, you need to follow the following steps: 1) Download and install the JDK, 2) Set environment variables, 3) Verify the installation, 4) Set the IDE, 5) Test the runner program. Setting up a JVM is not just about making it work, it also involves optimizing memory allocation, garbage collection, performance tuning, and error handling to ensure optimal operation.

ToensureJavaplatformindependence,followthesesteps:1)CompileandrunyourapplicationonmultipleplatformsusingdifferentOSandJVMversions.2)UtilizeCI/CDpipelineslikeJenkinsorGitHubActionsforautomatedcross-platformtesting.3)Usecross-platformtestingframeworkss

Javastandsoutinmoderndevelopmentduetoitsrobustfeatureslikelambdaexpressions,streams,andenhancedconcurrencysupport.1)Lambdaexpressionssimplifyfunctionalprogramming,makingcodemoreconciseandreadable.2)Streamsenableefficientdataprocessingwithoperationsli

The core features of Java include platform independence, object-oriented design and a rich standard library. 1) Object-oriented design makes the code more flexible and maintainable through polymorphic features. 2) The garbage collection mechanism liberates the memory management burden of developers, but it needs to be optimized to avoid performance problems. 3) The standard library provides powerful tools from collections to networks, but data structures should be selected carefully to keep the code concise.

Yes,Javacanruneverywhereduetoits"WriteOnce,RunAnywhere"philosophy.1)Javacodeiscompiledintoplatform-independentbytecode.2)TheJavaVirtualMachine(JVM)interpretsorcompilesthisbytecodeintomachine-specificinstructionsatruntime,allowingthesameJava

JDKincludestoolsfordevelopingandcompilingJavacode,whileJVMrunsthecompiledbytecode.1)JDKcontainsJRE,compiler,andutilities.2)JVMmanagesbytecodeexecutionandsupports"writeonce,runanywhere."3)UseJDKfordevelopmentandJREforrunningapplications.

Key features of Java include: 1) object-oriented design, 2) platform independence, 3) garbage collection mechanism, 4) rich libraries and frameworks, 5) concurrency support, 6) exception handling, 7) continuous evolution. These features of Java make it a powerful tool for developing efficient and maintainable software.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

VSCode Windows 64-bit Download
A free and powerful IDE editor launched by Microsoft

EditPlus Chinese cracked version
Small size, syntax highlighting, does not support code prompt function

WebStorm Mac version
Useful JavaScript development tools
