[C] 二分法搜索 →→→→→进入此内容的聊天室

来自 , 2020-05-31, 写在 C, 查看 130 次.
URL http://www.code666.cn/view/8c5f6ecd
  1. #include <stdlib.h>
  2. #include <stdio.h>
  3.  
  4. #define NELEMS(arr) (sizeof(arr) / sizeof(arr[0]))
  5.  
  6. int numarray[] = {123, 145, 512, 627, 800, 933};
  7.  
  8. int numeric ( const int *p1, const int *p2 )
  9. {
  10.         return ( *p1 - *p2 );
  11. }
  12.  
  13. int lookup ( int key )
  14. {
  15.         int *itemptr;
  16.  
  17.         /* The cast of (int(*)(const void *,const void*))
  18.            is needed to avoid a type mismatch error at
  19.            compile time */
  20.         itemptr = bsearch ( &key, numarray, NELEMS ( numarray ),
  21.                             sizeof ( int ), ( int ( * ) ( const void *,const void * ) ) numeric );
  22.         return ( itemptr != NULL );
  23. }
  24.  
  25. int main ( void )
  26. {
  27.         if ( lookup ( 512 ) )
  28.                 printf ( "512 is in the table.\n" );
  29.         else
  30.                 printf ( "512 isn't in the table.\n" );
  31.  
  32.         return 0;
  33. }

回复 " 二分法搜索"

这儿你可以回复上面这条便签

captcha