Search
 
SCRIPT & CODE EXAMPLE
 
CODE EXAMPLE FOR JAVA

binary search java

import java.util.*;
public class array
{
    static Scanner sc=new Scanner(System.in);
    public static void main(String[] args)
    {
        System.out.println("Enter the number of elements in the array:");
        int x=sc.nextInt();
        int arr[]=new int[x];
        System.out.println("Enter the sorted elements in the array:");
        for(int i=0; i<arr.length; i++)
        {
            arr[i]=sc.nextInt();
        }
        System.out.println("Enter the element to be searched for in the array:");
        int y=sc.nextInt();
        int max=arr.length-1;
        int min=0;
        int mid;
        while(max>=min)
        {
            mid=(min+max)/2;
            if(y==arr[mid])
            {
                System.out.println("The requested element is at index "+mid);
                break;
            }
            else if(y>arr[mid])
                min=mid+1;
            else if(y<arr[mid])
                max=mid-1;
            if(min>max)
                System.out.println("Requested element is not in the array.");
        }
    }
}
 
PREVIOUS NEXT
Tagged: #binary #search #java
ADD COMMENT
Topic
Name
4+2 =