Table of Contents
How BinarySearch() Method Works in Java?
Examples to Implement BinarySearch() in Java
Example #2
Conclusion
Recommended Article
Home Java javaTutorial BinarySearch() in Java

BinarySearch() in Java

Aug 30, 2024 pm 04:12 PM
java

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)
Copy after login

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:

  1. Suppose k is the key element that has to be searched for. Compare k with the array’s middle element.
  2. If k is matched with the element in the middle position, the mid-index has to be returned.
  3. 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.
  4. 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) );
}
}
Copy after login

Output:

BinarySearch() in Java

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.

BinarySearch() in Java

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);
}
}
Copy after login

Output:

BinarySearch() in Java

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 –

  1. JavaScript Math Functions
  2. Layout in Java
  3. Java Compilers
  4. 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!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

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

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1655
14
PHP Tutorial
1252
29
C# Tutorial
1226
24
Break or return from Java 8 stream forEach? Break or return from Java 8 stream forEach? Feb 07, 2025 pm 12:09 PM

Java 8 introduces the Stream API, providing a powerful and expressive way to process data collections. However, a common question when using Stream is: How to break or return from a forEach operation? Traditional loops allow for early interruption or return, but Stream's forEach method does not directly support this method. This article will explain the reasons and explore alternative methods for implementing premature termination in Stream processing systems. Further reading: Java Stream API improvements Understand Stream forEach The forEach method is a terminal operation that performs one operation on each element in the Stream. Its design intention is

PHP: A Key Language for Web Development PHP: A Key Language for Web Development Apr 13, 2025 am 12:08 AM

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

PHP vs. Python: Understanding the Differences PHP vs. Python: Understanding the Differences Apr 11, 2025 am 12:15 AM

PHP and Python each have their own advantages, and the choice should be based on project requirements. 1.PHP is suitable for web development, with simple syntax and high execution efficiency. 2. Python is suitable for data science and machine learning, with concise syntax and rich libraries.

PHP vs. Other Languages: A Comparison PHP vs. Other Languages: A Comparison Apr 13, 2025 am 12:19 AM

PHP is suitable for web development, especially in rapid development and processing dynamic content, but is not good at data science and enterprise-level applications. Compared with Python, PHP has more advantages in web development, but is not as good as Python in the field of data science; compared with Java, PHP performs worse in enterprise-level applications, but is more flexible in web development; compared with JavaScript, PHP is more concise in back-end development, but is not as good as JavaScript in front-end development.

PHP vs. Python: Core Features and Functionality PHP vs. Python: Core Features and Functionality Apr 13, 2025 am 12:16 AM

PHP and Python each have their own advantages and are suitable for different scenarios. 1.PHP is suitable for web development and provides built-in web servers and rich function libraries. 2. Python is suitable for data science and machine learning, with concise syntax and a powerful standard library. When choosing, it should be decided based on project requirements.

Java Program to Find the Volume of Capsule Java Program to Find the Volume of Capsule Feb 07, 2025 am 11:37 AM

Capsules are three-dimensional geometric figures, composed of a cylinder and a hemisphere at both ends. The volume of the capsule can be calculated by adding the volume of the cylinder and the volume of the hemisphere at both ends. This tutorial will discuss how to calculate the volume of a given capsule in Java using different methods. Capsule volume formula The formula for capsule volume is as follows: Capsule volume = Cylindrical volume Volume Two hemisphere volume in, r: The radius of the hemisphere. h: The height of the cylinder (excluding the hemisphere). Example 1 enter Radius = 5 units Height = 10 units Output Volume = 1570.8 cubic units explain Calculate volume using formula: Volume = π × r2 × h (4

PHP's Impact: Web Development and Beyond PHP's Impact: Web Development and Beyond Apr 18, 2025 am 12:10 AM

PHPhassignificantlyimpactedwebdevelopmentandextendsbeyondit.1)ItpowersmajorplatformslikeWordPressandexcelsindatabaseinteractions.2)PHP'sadaptabilityallowsittoscaleforlargeapplicationsusingframeworkslikeLaravel.3)Beyondweb,PHPisusedincommand-linescrip

PHP: The Foundation of Many Websites PHP: The Foundation of Many Websites Apr 13, 2025 am 12:07 AM

The reasons why PHP is the preferred technology stack for many websites include its ease of use, strong community support, and widespread use. 1) Easy to learn and use, suitable for beginners. 2) Have a huge developer community and rich resources. 3) Widely used in WordPress, Drupal and other platforms. 4) Integrate tightly with web servers to simplify development deployment.

See all articles