Binary search in java programming


import java.util.Scanner;

public class BinarySearch {

    public static void main(String[] args) {
        Scanner myScanner=new Scanner(System.in);
        System.out.print("Enter the array index : ");
        int n=myScanner.nextInt();
        int[] arr=new int[n];
        System.out.print("Enter "+n+" numbers : ");
        for (int i = 0; i <n; i++) {
            arr[i]=myScanner.nextInt();
        }
        System.out.print("Enter search number : ");
        int s=myScanner.nextInt();
        int f,l,m;
        f=0;
        l=n-1;
        m=(f+l)/2;
      
        while(f<=l)
        {
            if(arr[m]==s){
                System.out.print("The number is found in the array & Location is : "+(m+1));
                break;
            }
            else if(arr[m]<s){
                f=m+1;
            }
            else{
                l=m-1;
            }
            m=(f+l)/2;
        }
        if(f>l){
            System.out.println("The number is not found in the array");
        }
      
    }

}

Share this

Related Posts

Previous
Next Post »