×

Binary Search Java

Binary search is a search mechanism for key elements from the given List/Array. In Binary search, the search mechanism is followed by dividing the array into parts; hence the search mechanism is faster. Binary search is faster when compared to linear search; Binary search is faster.

For the binary, the elements in the array must be in sorted order. If the array is not in sorted order, you can sort the array using the Arrays. sort() method.

Binary Search Algorithm

The algorithm for binary search will describe the step by the procedure for searching the required key element. In this search, if the key element is found in the list, then it is a successful search, and it displays the index of the search key element as a result. Otherwise, it returns an unsuccessful search indicating that the key element is not found.

In Binary search, the searching mechanism follows the divide and conquer strategy in which the given array is divided into two parts, the left half and right half. The key element is then compared with the middle value of the list.

Algorithm

Binary_Search(a, lower_value, upper_value, key) // a is the array, a lower value is the first value, an upper value is a final value, and the key is the search element
Step 1: set beginning= lower_value, last = upper_value, position = - 1  
Step 2: repeat steps 3 and 4 while beginning <=last  
Step 3: set middle = (beginning + last)/2  
Step 4: if a[middle] = key  
set position = middle
print position  
go to step 6  
else if a[middle] > key 
set last = middle - 1  
else  
set beginning = middle + 1  
[end of if]  
[end of loop]  
Step 5: if position = -1  
print "The element is not in the list."  
[end of if]  
Step 6: exit  

The above algorithm will describe the process of searching.

BinarySearch.java

class BinarySearch{  
 public static void binarySearch(int arr[], int low, int high, int k){  
   int mid = (low + high)/2;  
   while( low <= high){  
      if ( arr[mid] < k){  
        low = mid + 1;     
      }else if ( arr[mid] == k ){  
        System.out.println("The index of the element: " + mid);  
        break;  
      }else{  
         high = mid - 1;  
      }  
      mid = (low+ high)/2;  
   }  
   if ( low > high ){  
      System.out.println("The key element is not founded");  
   }  
 }  
 public static void main(String args[]){  
        int arr[] = {1,2,3,4,5};  
        int k = 3;  
        int high=arr.length-1;  
        binarySearch(arr,0,high,k);     
 }  
} 

Output:

Binary Search Java

Binary Search Using Recursion

Binary search can also be done using the recursion.

BinarySearchRecursion.java

class BinarySearchRecursion{  
    public static int binarySearch(int arr[], int low, int last, int key){  
        if (last>=low){  
            int mid = low+ (last - low)/2;  
            if (arr[mid] == key){  
            return mid;  
            }  
            if (arr[mid] > key){  
            return binarySearch(arr, low, mid-1, key);// the left sub array is searched
            }else{  
            return binarySearch(arr, mid+1, last, key);//the right sub array is searched
            }  
        }  
        return -1;  
    }  
    public static void main(String args[]){  
        int arr[] = {1,2,3,4,5};  
        int key = 3;  
        int last=arr.length-1;  
        int res = binarySearch(arr,0,last,key);  
        if (res == -1)  
            System.out.println("The element is not present");  
        else  
            System.out.println("The index of the element: "+res);  
    }  
}  

Output:

Binary Search Java

Binary search using  Arrays.binarySerach() Method

In the binarySearch() method, the code will be simple. Let us understand this with the simple program.

BinarySearchMethod. java

import java.util.Arrays;  
class BinarySearchMethod{  
    public static void main(String args[]){  
        int arr[] = {1,2,3,4,5};  
        int key = 3;  
        int res= Arrays.binarySearch(arr,key);  
        if (res< 0)  
            System.out.println("The Element is not founded!");  
        else  
            System.out.println("The element found at the index: "+res);  
    }  
}  

Output

Binary Search Java

This way, the binary search can be in the group of elements. The Time complexity for binary search is O(log N) for the Average case and O(1) in the case of the best case Time Complexity.


Related Topics

Java Finally Keyword

The final block in Java is used to run essential code, such as connection closure, among other things. Whether an exception is resolved or not, the Java finally block has...

3 minutes read.

Java Architecture

Java architecture is a combination of three parts they are JVM, JRE and JDK. These components will help in the functioning of the java programs. The process of code interpretation...

6 minutes read.

Lambda expressions in Java

A brief introduction to Lambda expression in java In this topic, we will discuss the lambda expression in java. A lambda expression in Java is an enhanced version of an anonymous...

13 minutes read.

How to Update Java

As we all know that java can be installed in all operating systems like windows, Linux, macOS. We are available with the java 17 and java 18 versions in the...

3 minutes read.

JDBC vs ODBC

Difference Between JDBC and ODBC ODBC: ODBC (Open Database Connectivity) is the accepted method for accessing databases among organisations and programmers. A database is linked to other programmes, such as word processors, spreadsheets,...

4 minutes read.

Cosmic Superclass in Java

The parent class of all Java classes is the Object class. The Java Object class is the parent of all Java classes, whether directly or indirectly. The Object class is...

6 minutes read.

How to resolve Illegal state exceptions in Java

What is IllegalStateException? When a method is called at the incorrect time, a runtime exception called an IllegalStateException is raised in Java. This exception is utilized to show that a method...

3 minutes read.

Hello Program in Java

Hello Program in Java The Hello program in Java displays the word Hello on the console. It is the basic program in Java. In this section, we will learn different ways...

3 minutes read.

Difference between Static and Instance Methods in Java

Static Method in Java The static technique has a place with the class as opposed to the object of the course. These are intended to be divided between every one of...

10 minutes read.

Java Map Interface

A map is a collection that maps keys to values, with no duplicate keys allowed. The elements in a map are key/value pairs. HashMap: HashMap stores the keys in a...

3 minutes read.

Conditional operator in Java

In Java, there are around eight operators, and among them, three operators are used to evaluate the condition and decide the Result based on the Result of the evaluated condition. Below...

4 minutes read.

Difference between JIT and JVM in Java

In this tutorial, we will discuss the difference between JIT (Just In Time Compiler) and JVM (Java Virtual Machine) in Java. Before we move to the differences, let's understand what...

4 minutes read.

Java Integer remainder Unsigned() method

The remainderUnsigned() method of Java Integer class returns the unsigned remainder by dividing the first and second argument. Syntax public static int remainderUnsigned(int dividend, int divisor)  Parameters The ‘dividend’ and ‘divisor’ represents the value...

1 minute read.

String isnullorempty in Java

What do you mean by String? Strings are a collection of characters that are commonly used in Java programming. Strings are regarded as objects in the Java programming language. “String” is a...

4 minutes read.

How to Convert Octal to Decimal in Java

How to Convert Octal to Decimal in Java There are two methods to convert Octal to Decimal: Using parseInt() method Using user-defined logic Using Integer.parseInt() method The Integer.parseInt() method is a static method...

2 minutes read.

Java Boolean Keyword

Boolean keyword In java programming language we basically have two types of primitive data types, Boolean and Numeric (integer and floating-point data types). In this article we are going to learn...

4 minutes read.

Java vs Node.js

Java: Java is an object oriented programming language. It is also known as multi threaded language. It was designed by James gosling in the year 1995. We can also say that...

4 minutes read.

JAR File in Java

What is a JAR File? JAR stands for Java Archive. It is a file format mainly used to combine many Java class files and the corresponding metadata and resources into one...

4 minutes read.

Blockchain in Java

Blockchain is a continuously expanding ledger that maintains an immutable, secure, and chronological record of all transactions that have ever occurred. It can be utilized to securely transfer money, assets,...

9 minutes read.

Tower of Hanoi Program in Java

Tower of Hanoi Program in Java The Tower of Hanoi program in Java is written to solve a mathematical puzzle, called Tower of Hanoi, where we have three poles and n...

4 minutes read.