Binary Search in C Arrays – An Example

By | July 13, 2011

Hi,

Want to search for an item in C Arrays, using Binary Search ? Use the following sample of code to search in C Arrays using Binary Search.


#include <stdio.h>
#define SIZE 10

int binarySearch( const int b[], int searchKey, int low, int high );

int main() {
   int arr[ SIZE ];
   int i;
   int key = 5;
   int result = -1;

   for ( i = 0; i < SIZE; i++ ) {
      a[ i ] = 2 * i;
   }

   result = binarySearch( arr, key, 0, SIZE - 1 );

   if ( result != -1 ) {
      printf( "n%d is in the array %dn", key, result );
   } else {
      printf( "n%d Not in the array!n", key );
   }

   return 0;

}

int binarySearch( const int b[], int searchKey, int low, int high )
{
   int middle;

   while ( low <= high ) {
      middle = ( low + high ) / 2;

      if ( searchKey == b[ middle ] ) {
         return middle;
      } else if ( searchKey < b[ middle ] ) {
         high = middle - 1;
      } else {
         low = middle + 1;
      }
   }
   return -1;

}

Guess the output!
🙂

Leave a Reply

Your email address will not be published. Required fields are marked *