C/C++ 內建(二元搜尋樹)(Binary Search Tree) [stdlib.h bsearch()] 函示庫


資料來源: https://pydoing.blogspot.com/2010/07/c-bsearch.html

https://www.runoob.com/cprogramming/c-function-bsearch.html


線上編譯: https://www.tutorialspoint.com/compile_c_online.php


程式01:

#include 
#include 
 
int cmp(const void *s1, const void *s2);
 
int main(void)
{
    char *vowel = "AEIOUaeiou";
    char *test1 = "thesaurus";
    char *test2 = "Apple";
    char *ptr;
     
    ptr = bsearch(test1, vowel, 10, sizeof(*test1), cmp);    
    if (ptr) {
        printf("%s的第一個字母是母音...\n", test1);
    }
    else {
        printf("%s的第一個字母不是母音...\n", test1);
    }
     
    ptr = bsearch(test2, vowel, 10, sizeof(*test2), cmp);    
    if (ptr) {
        printf("%s的第一個字母是母音...\n", test2);
    }
    else {
        printf("%s的第一個字母不是母音...\n", test2);
    }
    
    return 0;
}



int cmp(const void *s1, const void *s2)
{
    return *(char *)s1 - *(char *)s2;
}


程式02:

#include 
#include 
 
 
int cmpfunc(const void * a, const void * b)
{
   return ( *(int*)a - *(int*)b );
}
 
int values[] = { 5, 20, 29, 32, 63 };
 
int main ()
{
   int *item;
   int key = 32;
 
   /* 使用 bsearch() 在數組中查找值 32 */
   item = (int*) bsearch (&key, values, 5, sizeof (int), cmpfunc);
   if( item != NULL ) 
   {
      printf("Found item = %d\n", *item);
   }
   else 
   {
      printf("Item = %d could not be found\n", *item);
   }
   
   return(0);
}

相關文章