Binary Search in Java

In this article we are implementing binary search in java. Binary search is one of the most efficent searching algorithm aplicable only on sorted arrays. Here we are going to write the binary search program in java. if you want to learn about binary search algorithm you can check our post on binary search algorithm here https://gangforcode.com/binary-search-algorithm/

Binary Search algorithm:-

binary search in java

BinarySearch(array,search item)

Here array is a sorted array and the search item is given the information we have to search in the given array. We have to search in the array.

Steps:-

  1. Initilize low with 0 and high with length of array-1. and mid=(low+high)/2.
  2. Repeat Step 3 and 4 while low<=high and array[mid] not equal to i search item.
  3. if search item<array[mid] then set high =mid-1 else set low = mid+1.
  4. set mid=int(low+high)/2. End of stvep 2 loop.
  5. if arrray[mid]=search item,then set search item is found at location mid. else not found.
  6. exit

Java code for binary search:-


package gangforcode;
import java.util.*;
public class binarySearch {
public static void main(String[] args) {
    Scanner sc = new Scanner(System.in);
    System.out.println("Enter the size of array");
    int n=sc.nextInt();
    int[]a=new int[n];
    System.out.println("Enter the elements of array");
    for(int i=0;i<n;i++) {
        a[i]=sc.nextInt();
        }
    System.out.println("enter search element");
    int search=sc.nextInt();
    int result=binary(a,search);
    if(result==-1) {
        System.out.println("search element not found");
    }
    else {
        System.out.println("search element found at index   "+ result);
    }

}

public static int binary(int[]a, int search) {
int low=0;
int high=a.length-1;
int mid=(int)(low+high)/2;
while(low<=high && a[mid]!=search) {
if(search<a[mid]) {
high=mid-1;}
else {
low=mid+1;
}
mid=(int)(low+high)/2;

}
if(a[mid]==search) {
    return mid;
}
else {
    return-1;
}

}

Output:-

binary search in java

In the same way we can write code for binary search in other programming languages like C, C++, Python etc.

Similar Java tutorials –

Hello World – https://gangforcode.com/java-code-to-print-hello-world/
data types in java – https://gangforcode.com/data-types-in-java/
identifiers in java – https://gangforcode.com/identifiers-in-java/
keywords in java – https://gangforcode.com/keywords-in-java/
Multidimensional Array in Java – https://gangforcode.com/multidimensional-array-in-java/
Matrix Addition in Java – https://gangforcode.com/matrix-addition-in-java/

1 thought on “Binary Search in Java”

Leave a Comment