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

You have accidentally left your suitcase behind when you got off the train. You only realized it after the train left the platform. Write a letter to the station master reporting your loss and request that the suitcase is located and kept till you claim it.

Write a letter to the Transport Officer describing him about the Deplorable State of the Public Transport | Study Table