Rotate your phone or change to desktop for better experience

Rotate your phone or change to desktop for better experience

java binary search || java

 import java.util.*;

public class Main{

    

    public static int binsearch(int arr[],int size , int key)

    {

        int h= size-1;

        int l= 0;

        int mid=0;

        int i=1;

        

        while ( l <= h)

        {

             mid = (l+h)/2;

            //System.out.println(i++);

            if (key == mid)

            return mid-1;

            else if ( key <=mid)

            h= mid-1;

            else 

            l = mid +1;

        }

        return -1;

        

    }

    

    public static void main(String[] args)

    {

        Scanner sc = new Scanner(System.in);

        

        System.out.println("Enter the size of the array");

        int size = sc.nextInt();

        int [] arr = new int[size];

        

        System.out.println("Enter the array elements");

        for(int i = 0 ; i < size ; i++)

        {

            arr[i]= sc.nextInt();

        }

        

        System.out.println("enter the key");

        int key = sc.nextInt();

        

        int ans = binsearch(arr,size,key);

        if(ans > 0)

        System.out.println("Element is precent on Index : "+ans);

        else 

        System.out.println("Elemet in not precent on Index");


    }

}

Post a Comment

0 Comments