c的二分查找函数bsearch

    技术2022-05-11  111

    #include <ubase.h>#include "My850Page.h"#include "stdlib.h"  //注意这里#include "iostream.h"#include "iomanip.h"

    /*void*  bsearch (  const void * key, //待查找单元的关键字  const void * base,  //在什么地方找 size_t num,   //有多少单元可以查找 size_t width,   //每个单元占多少字节 int (*fncompare)(const void *, const void * )  //怎样比较两个元素大小 ); */

    #define MAX 100

    void hello(void);

    int cmp( const void *a , const void *b ){ int x = *(int*)a; int y = *(int*)b; return x - y;}

    void hello(void){ // TODO: Add code here ...  CMy850Page *page = new CMy850Page; page->Create(NULL, "Hello world"); page->DoModal(); delete page;}

    int main(void){ //uBaseSetLang(UBASE_LANG_CHS); //GB2312// uBaseSetLang(UBASE_LANG_CHT); //BIG5// uBaseSetLang(UBASE_LANG_ENG); //ENGLISH

     //hello(); // TODO: Add code here ...

     int map[MAX]; int n = 10; int key; int *item; int i;

     for( i = 0 ; i < n ; i++ ) { map[i] = i * i + 3 * i + 4; }

     //cout<<""<<endl; printf("数列:/n"); for( i = 0 ; i < n ; i++ ) {  printf("]",map[i]); } //cout<<setw(5)<<map[i]; //cout<<endl; printf("/n");

     key = 44; item = (int*)bsearch( &key , map , n , sizeof(int) , cmp );

    /*void*  bsearch (  const void * key, //待查找单元的关键字  const void * base,  //在什么地方找 size_t num,   //有多少单元可以查找 size_t width,   //每个单元占多少字节 int (*fncompare)(const void *, const void * )  //怎样比较两个元素大小 ); */

     if( item != NULL ) {  //cout<<"指定数 "<<*item<<" 在数列中"<<endl;  printf("指定数 %d 在数列中/n",*item); } else {  //cout<<"找不到指定数 "<<*item<<endl;  printf("找不到指定数 %d/n",*item); }

     

     USleep(30000);

     return 0;}

     


    最新回复(0)