Friday, September 17, 2010

Binary Search on unsorted array(Sort with bubble sort)

package binarysearch;
import java.io.*;
class bnsearch
{
    int a[],low=0,n=0,flag=0,temp,high=0,key;
    int i,mid,j,item;
    public void setSize(int max)
        {
            a=new int[max];
        }
    public void insert (int item)throws NullPointerException
        {
            a[n]=item;
            n++;
        }
    public void display()
        {
        for(i=0;i
             System.out.println(a[i]+"\t");
        }
    public void sort()
        {
        for(i=0;i
         {
             for(j=0;j<(n-i-1);j++)
                 {
                 if(a[j]>a[j+1])
                 {
                    temp=a[j+1];
                    a[j+1]=a[j];
                    a[j]=temp;
                 }
                }
            }
        for(i=0;i
             System.out.println(a[i]+"\t");
        }
    public void search(int key)
         {
        high=n-1;
            while(low<=high)
            {
                mid=(low+high)/2;

              if(a[mid]==key)
              {
                  flag=1;
                  break;
                 }
              else if(a[mid]
                           low=mid+1;
              else
                           high=mid-1;
            }
    if(flag==1)
                {
                System.out.println("the element to be found");
                System.out.println("the element is in"+(mid+1)+"th position");
                }
            else
                System.out.println("element is not found");
         }
}
  public class Main
  {
      public static void main(String[] args)throws IOException
            {
                int h,n=0,t,k;
                System.out.println("enter the number of elements");
                InputStreamReader isr=new InputStreamReader(System.in);
                BufferedReader br=new BufferedReader(isr);
                h=Integer.parseInt(br.readLine());
                bnsearch b=new bnsearch();
                b.setSize(h);
                System.out.println("enter the elements");
                for(n=0;n
                    {
                         InputStreamReader isr1=new InputStreamReader(System.in);
                         BufferedReader br1=new BufferedReader(isr1);
                         t=Integer.parseInt(br1.readLine());
                         b.insert(t);
                       }               
                                          b.sort();
                System.out.println("enter the element to be searched");
                InputStreamReader isr2=new InputStreamReader(System.in);
                BufferedReader br2=new BufferedReader(isr2);
                k=Integer.parseInt(br2.readLine());
                b.search(k);
                b.display();
            }
    }

No comments:

Post a Comment