×

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

How to Solve the Deprecated Error in Java?

Deprecated Java methods should not be used because they are deprecated (often, there are better, more modern alternatives). API update. Until now, Java has kept everything backward compatible and never...

3 minutes read.

Transaction Management in java

Definition: A database application is an application that is running against a relational database and executes one or more transactions. A transaction is an executing program that contains some database operations,...

4 minutes read.

How to stop execution after a certain time in Java

We will learn how to stop a long-running execution after a set amount of time in this post. We will take a look at a few alternative approaches to this...

6 minutes read.

Byte to Hex in Java

Java exclusively uses byte data types to store in a byte array, which is an array. Each component of a byte array has a default value of 0. Hex String -...

3 minutes read.

Best Java IDE

Applications for desktop, workplace, smartphone, and the internet can be created using Java, one of the most popular programming languages. Java will undoubtedly be a popular programming language for so...

5 minutes read.

How to add 24 Hours to Date in Java?

In this tutorial, we will learn how to add 24 hours to the local or current date in Java language. We will begin our topic with basic concepts and would...

2 minutes read.

Bellman Ford Algorithm in Java

Numerous algorithms have been used in dynamic programming to determine the shortest path inside a graph. Among them are Floyd, all-pair shortest path problem, Breadth First Search, Depth First Search,...

6 minutes read.

Alien language problem in Java

Given the alphabetic sequence of an alien language, given a sorted dictionary (array of words) for the languages. Example: Words = { "aac", "abc", "aaa" } Output c, a, b Algorithm: (1) Compare two words that...

3 minutes read.

Java Math incrementExact() Method

The incrementExact() method of Math class returns the argument incremented by one, throwing an exception if the result overflows an int or a long. Syntax: public static int incrementExact (int a)public static...

1 minute read.

Class vs Object in Java

Java : Java is a pure object oriented language. It was introduced by James Gosling in the year 1995. The first public implementation of java was done by sun micro systems...

7 minutes read.

Thread States in Java

An Item's Life Cycle (Thread States) A thread can be in any of the states mentioned above at any given time in Java. They are as follows: New Active I'm blocked or waiting Temporary...

3 minutes read.

Java Program to generate binary numbers

A binary tree can create binary numbers ranging from 1 to n. Every node in a tree, the right, and left nodes, has two children, as is common knowledge. The...

3 minutes read.

How to Calculate Time Difference Between Two Dates in Java?

Date is being used extensively in Java to calculate date differences. While constructing an application, the date of joining an organisation, admission date, appointment date, and others might be included....

4 minutes read.

Print Matrix Diagonally in Java

The aim is to print the elements of a matrix of size n*n in some kind of a diagonal pattern. Input : mat[3][3] = {{1, 2, 3},                      {4, 5, 6},                      {7,...

3 minutes read.

Copy data/content from one file to another in java

In this article, you will be acknowledged about how to copy data or content from one file to another file. Also, you will be acknowledged about the classes and methods...

3 minutes read.

How to Split the String in Java with Delimiter

In Java, splitting strings is a significant and typically used activity while coding. Java gives different ways of dividing the String. The most widely recognized way is to use the...

3 minutes read.

Java Pi

What is Pi? There are many formulas in geometry that employ the Pi constant to calculate things like circumference, area, and volume. A circle's circumference divided by its diameter yields a...

3 minutes read.

Differences between Set and List in Java

Set in Java: The Java. util package contains an interface called the set. The set interface expands the Collection interface. A collection interface is an unordered collection of List where duplicates...

6 minutes read.

Loose Coupling in Java

Loosely coupling mechanism in java means one reference of a variable capable of holding multiple implementation class memory is called loosely coupling. Or in other words, one interface reference variable...

3 minutes read.

Creating a Jar file in Java

The JDK's jar (Java Archive) tool offers the ability to produce jar files that can be executed. If you double-click a jar file that is executable, it will call the...

2 minutes read.