×

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

Enterprise Java Beans

One of the many Java APIs for the common development of corporate software is Enterprise Java Beans (EJB). An EJB, a server-side software component, contains the business logic of an...

4 minutes read.

House Numbers in Java

In this section, we will discuss about house number in Java. It is a sum of cubes, each of which has a dimension of h + 1. There is a...

3 minutes read.

Kotlin Vs Java

Kotlin Vs Java There are many languages available for Android development. Java is the official language for android development but Kotlin is becoming popular nowadays. This article discusses both of these...

4 minutes read.

Reverse a String using Collections in Java

Generally, a String is a grouping of characters. Yet, in Java, a String is an item that addresses a succession of characters. The Java.lang.String class is utilized to make a...

5 minutes read.

Least Operator to Express Number in Java

In this article, we will learn about how to obtain a target number using a single number or a single integer by leveraging least operators in Java. There can be...

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.

Java Vs C++

Java Vs C++ Java and C++ both are Object Oriented Programming languages. Both languages are popular for competitive programming. C++ is used by many coders who have just started learning programming...

4 minutes read.

String Array in Java

String Array in Java An array is alinear data structure that stores similar type of data. It allows us to store fixed number of elements.It can be of different data types...

6 minutes read.

Pyramid Program in Java

Pyramid Program in Java In the previous section, we have discussed about the number pattern programs in Java. The logic for the number pattern and pyramid pattern is the same except...

2 minutes read.

Packages Program in java

Let us know what package is in the Java programming language, and later we will learn about types of packages and how to define a package. How to import Java...

4 minutes read.

How to Reduce Time Complexity in Java

What is time complexity?  The time complexity in java is given as the amount of time a program requires to run or execute it Calculating the time complexity of the program The time...

4 minutes read.

Check if the given array is mirror inverse in Java

The primary objective is to check whether the given array is mirror inverse or not. The values and position of the specified array are switched, and a duplicate array is created....

3 minutes read.

Bubble Sort in Java

Bubble Sort in Java Bubble sort isalso known as sinking sort. It is one of the simplest sorting algorithms. In the bubble sort algorithm, the given array is traversed from left...

5 minutes read.

Constructor Program in Java

Constructor Program in Java In Java, a constructor is a piece of code that is used to create an object. A constructor is called implicitly when an object is created in...

7 minutes read.

Adapter class in Java

By using the adapter classes, we can implement Listener interfaces. With the help of adapter classes, we can save code as it provides all implementation methods of listener interfaces Advantages of...

3 minutes read.

Java BufferedWriter

BufferWriter Class: It is used to write the data more efficiently. This class is present in the java.io package, it inherits the data from the Writer class. Writer class is...

4 minutes read.

Java Constant

A constant is an unchangeable entity in coding, as its title implies. The value which cannot be altered, in other terms. We shall understand about Java constants and exactly how...

3 minutes read.

List of Constants in Java

In this tutorial, we are going to deal with constants available in Java.Every programming language has its constants. Similarly, Javaalso has got constants of its own. In this tutorial, we will...

6 minutes read.

Stack vs Heap in Java

In Java, whenever we declare an object or create a variable, whether it is an instance variable, local variable, or static variable, a certain memory is used to store the...

4 minutes read.

Java Boolean logicalOr() Method

The logicalOr() method of Java Boolean class returns the result of implementing logical OR operation on the specified Boolean operands. Syntax: public static boolean logicalOr (boolean a, boolean b) Parameters: The parameters ‘a’ and...

2 minutes read.