Binary Search Program for Java | Study Table

 import java.util.Scanner;

public class BinarySearch
{
    public static void main(String args[])
    {
        Scanner scanner = new Scanner(System.in);
        System.out.println("Enter array Strength: ");
        int array[] = new int[scanner.nextInt()];
        System.out.println("Enter array Elements: ");
        for(int i=0; i<array.length; i++) array[i] = scanner.nextInt();

        for(int i=0; i<array.length; i++)
        {
            for(int j=0; j<array.length-1; j++)
            {
                int temp = 0;
                if(array[j]>array[j+1])
                {
                  temp = array[j];
                  array[j] = array[j+1];
                  array[j+1] = temp;  
                }
            }
        }
        System.out.println("Enter the Element to be Searched: ");
        int srch = scanner.nextInt();
        int lLimit=0, uLimit=array.length-1, mid=0, flag=0;
        while(lLimit<=uLimit)
        {
            mid = (lLimit + uLimit)/2;
            if(array[mid]<srch) lLimit = mid+1;
            else if(array[mid]>srch) uLimit = mid-1;
            else
            {
                flag++;
                break;
            }
        }
        System.out.println("The Entered array is: ");
        for(int i:array) System.out.print(i+" ");
        if(flag>0) System.out.println("\nSearch element found at position "+(mid+1));
        else System.out.println("Search Element Not found!");
        scanner.close();
    }    
}

Comments

Popular posts from this blog

Java Program for Binary to Decimal Conversion | Study Table

[ ICSE ] Write a Letter to a Bookseller, complaining that the books supplied by him were not the latest Editions, though you have paid the money according to the latest Editions as given in the Bookseller's Catalogue. Request him to send you the latest Editions of the books and assure him that you would send back the old edition books supplied by him | Study Table