You are on page 1of 1

BINARY SEARCH

#inc lude<std io .h>


#inc lude<con io .h>
vo id main ( )
{
i n t f l ag=0 ,a [20 ] ,n ,pos , i , i t em, low ,h igh ,m id ;
vo id so r t ( i n t [ ] , i n t ) ;
c l r sc r ( ) ;
pr in t f ( " \nEn te r the no . o f number : \ t " ) ;
scan f ( "%d" ,&n) ;
pr in t f ( " \nEn te r the numbers \n " ) ;
f o r ( i=1 ; i<=n; i++)
scan f ( "%d" ,&a[ i ] ) ;
so r t (a ,n ) ;
pr in t f ( " \nEn te r the data to be sea rched : \n " ) ;
scan f ( "%d" ,& i tem) ;
l ow=1;
h igh=n;
whi le ( l ow<=h igh )
{
mid=( low+h igh ) /2 ;
i f ( i t em==a[mid ] )
{
f l ag=1;
break ;
}
e l se i f ( i t em>a[mid ] )
l ow=mid+1;
e l se
h igh=mid - 1 ;
}
i f ( f l ag==0)
pr in t f ( " \nThe e lement %d i s not presen t i n the ar ray \n" , i t em) ;
e l se
pr in t f ( "The e lement %d i s presen t i n the ar ray" , i t em) ;
getch ( ) ;
}
vo id so r t ( i n t a[ ] , i n t n)
{
i n t i , j , t emp;
f o r ( i=1 ; i<=n-1 ; i++)
f o r ( j= i+1 ; j<=n; j++)
i f ( a [ i ]>a [ j ] )
{
temp=a[ i ] ;
a[ i ]=a[ j ] ;
a[ j ]=temp;
}
}

1 | Page binary search coding

You might also like