Friday, April 8, 2016

Binary Search


  Write a simple binary code for Search in  c programming language.



#include <stdio.h>
int  main () {


 int a [ 10 ], i, n, m, c = 0 , l, u, mid;


 printf ( "Enter The array Size:\n" );
 scanf ( "%d" , & n);


 printf ( "Enter The Elements In Ascending Order:\n" );
 for (i = 0 ; i < n; i ++ ) {
      scanf ( "%d" ,&a[i]);
  }


 printf ( "Enter Number To Search:\n" );
 scanf ( "%d",&m);


 l = 0 ;
 u = n - 1 ;

 while (l <= u) {
    mid = (l + u) / 2 ;
    if (m == a [mid]) {
       c = 1 ;
       break ;
     }
   else  if (m < a [mid]) {
      u = mid - 1 ;
     }
   else
      l = mid + 1 ;
   }
 if ( c == 0 )
     printf ( "The Number Is Not Found." );
 else
  printf ( "The Number Is Found." );

 return  0 ;
 }





Share this

0 Comment to "Binary Search"

Post a Comment