Binary search

 

// 2. Binary search

import java.io.*;

import java.util.*;

 

class BinarySearch

{

     public static void main(String [] as) throws IOException

     {

          Scanner sc = new Scanner(System.in);

          int i, ele, arrlen, pos=-1;

          int top, bottom, mid;

         

          System.out.print("Enter array length : ");

          arrlen = sc.nextInt();

         

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

          int arr[] = new int[arrlen];

          for(i=0;i<arrlen;i++)

              arr[i]=sc.nextInt();

         

          System.out.print("Enter element to search : ");

          ele = sc.nextInt();

         

          // Sort the input array

          Arrays.sort(arr);

         

          System.out.print("Entered array (sorted) : ");

          for(i=0;i<arrlen;i++)

              System.out.print(arr[i]+"  ");

         

          bottom = 0;

          top = arrlen-1;

 

          while(true)

          {

              if (bottom > top)

              {

                   System.out.println("\nElement not found in array.");

                   break;

              }

                  

              mid = (int)(bottom+top)/2;

 

              if(arr[mid] == ele)

              {

                   System.out.println("\nElement present in array.");

                   break;

              }

             

              else if (arr[mid] < ele)

                   bottom = mid + 1;

 

              else

                   top = mid - 1;

          }

     }

}

No comments:

Post a Comment

Don't be a silent reader...
Leave your comments...

Anu