Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

Binary Search Program in Java

Hi friends, hope you are doing good! In this tutorial, I am going to share a Java Program to find the number using binary search program in Java programming language.

Binary Search program in Java

Copy the below Java program and execute it with the help of Java compiler. At the end of this tutorial, I have shared the output of this program more understandable.

class BinarySearchExample1 
{
public static int binarySearch(int arr[], int first, int last, int key){
    if (last>=first){
        int mid = first + (last - first)/2;
        if (arr[mid] == key){
        return mid;
        }
        if (arr[mid] > key){
        return binarySearch(arr, first, mid-1, key);//search in left subarray
        }else{
        return binarySearch(arr, mid+1, last, key);//search in right subarray
        }
    }
    return -1;
}
public static void main(String args[]){
    int arr[] = {10,20,30,40,50,60,70};
    int key = 70;
    int last=arr.length-1;
    int result = binarySearch(arr,0,last,key);
    if (result == -1){
        System.out.println("Element is not found!");
    }
    else{
      System.out.println("Element is found at index: "+result);
    }
}
}

Program Output

Element is found at index: 6

Liked this tutorial? Do Like & share with your friends

The post Binary Search Program in Java appeared first on FreeWebMentor.



This post first appeared on Programming Blog Focused On Web Technologies, please read the originial post: here

Share the post

Binary Search Program in Java

×

Subscribe to Programming Blog Focused On Web Technologies

Get updates delivered right to your inbox!

Thank you for your subscription

×