C Tutorial/Array/Array Search

Материал из C\C++ эксперт
Перейти к: навигация, поиск

Binary search of an array

<source lang="cpp">#include <stdio.h>

  1. define SIZE 15

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

  int a[ SIZE ];
  int i;
  int key = 10;
  int result = -1;
  for ( i = 0; i < SIZE; i++ ) {
     a[ i ] = 2 * i;
  }
  result = binarySearch( a, key, 0, SIZE - 1 );
  if ( result != -1 ) {
     printf( "\n%d found in array element %d\n", key, result );
  } else {
     printf( "\n%d not found\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;

}</source>

10 found in array element 5

Linear search of an array

<source lang="cpp">#include <stdio.h>

  1. define SIZE 100

int linearSearch( const int array[], int key, int size ); int main() {

  int a[ SIZE ]; 
  int x; 
  int searchKey; 
  int element; 
  for ( x = 0; x < SIZE; x++ ) { 
     a[ x ] = 2 * x;
  } 
  printf( "Enter integer search key:\n" );
  scanf( "%d", &searchKey );
  element = linearSearch( a, searchKey, SIZE );
  if ( element != -1 ) {
     printf( "Found value in element %d\n", element );
  } 
  else {
     printf( "Value not found\n" );
  } 
  return 0;

} int linearSearch( const int array[], int key, int size ) {

  int n;
  for ( n = 0; n < size; ++n ) {
     if ( array[ n ] == key ) { 
        return n;
     } 
  } 
  return -1;

}</source>

Enter integer search key:
2
Found value in element 1