#include <stdio.h> #include <stdlib.h> #define MAX 20 int intcmp(const void *v1, const void *v2); int main(void){ int arr[MAX], count, key, *ptr; //提示用戶輸入一些整數 printf("Enter %d integer values; press Enter each.\n", MAX); for(count = 0; count < MAX; count++){ scanf("%d", &arr[count]); } puts("Press Enter to sort the values."); getc(stdin); //將數組中的元素按升序排列 qsort(arr, MAX, sizeof(arr[0]), intcmp); //顯示已排列的數組元素 for(count = 0; count < MAX; count++){ printf("\narr[%d] = %d.", count, arr[count]); } puts("\nPress Enter to continue."); getc(stdin); //輸入要查找的值 printf("Enter a value to search for: "); scanf("%d", &key); //執行查找 ptr = (int *)bsearch(&key, arr, MAX, sizeof(arr[0]), intcmp); if(ptr != NULL){ printf("%d found at arr[%d].", key, (ptr - arr)); } else { printf("%d not found.", key); } return 0; } int intcmp(const void *v1, const void *v2){ return (*(int *)v1 - *(int *)v2); } /*用qsort()和bsearch()對字符串進行排序和查找*/ #include <stdio.h> #include <stdlib.h> #include <string.h> #define MAX 20 int comp(const void *s1, const void *s2); int main(void){ char *data[MAX], buf[80], *ptr, *key, **key1; int count; //輸入單詞或短語 printf("Enter %d words or phrases, pressing Enter after each.\n", MAX); for(count = 0; count < MAX; count++){ printf("Word %d: ", count + 1); gets(buf); data[count] = malloc(strlen(buf)+1); strcpy(data[count], buf); } //排列字符串(其實是排列指針) qsort(data, MAX, sizeof(data[0]), comp); //顯示已排列的字符串 for(count = 0; count < MAX; count++){ printf("\n%d: %s", count + 1, data[count]); } //提示用戶輸入待查找的單詞 printf("\n\nEnter a search key: "); gets(buf); // Perform the search. First, make key1 a pointer // to the pointer to the search key. key = buf; key1 = &key; ptr = bsearch(key1, data, MAX, sizeof(data[0]), comp); if(ptr != NULL){ printf("%s found.\n", buf); } else { printf("%s not found.\n", buf); } return (0); } int comp(const void *s1, const void *s2){ return (strcmp(*(char **)s1, *(char **)s2)); }