BINARY SEARCH

 import java.util.*;

 class binary_search

 {

      void main()

      { 

          Scanner ob=new Scanner (System.in);

          int a[]=new int[6],i,beg=0,end=5,m=0,f=0,pos=0,num;

          System.out.println("Enter the elements in thsw asceending order");

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

          {

               a[i]=ob.nextInt();

            }

            System.out.println("Enter the element to be searchede");

            num=ob.nextInt();

            while(beg<=end)

            {

                m=(beg+end)/2;

                if(num==a[m])

                {

                    f=1;

                    pos=m;

                    break;

                }

                else if(num>a[i])

                beg=m+1;

                else if(num<a[m])

                end=m-1;

            } 

            if(f==1)

            {

                System.out.println(num+"is found at"+pos+"index position");

                System.out.println(num+"is found at"+(pos+1)+"place/position");

            }

            else

            System.out.print("the search is unsucssesful");

        }

    }

 

Post a Comment

Please Select Embedded Mode To Show The Comment System.*

Previous Post Next Post

It looks like you're using an ad blocker. We rely on ads to keep our site free, please whitelist us!

Click here to continue

Please whitelist our site to continue enjoying our content.

Whitelist | Close