#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <string.h>
#define oops(msg) {perror(msg); exit(errno);}
#define NUM 7
/*
#include <stdlib.h>
void *bsearch(const void *key, const void *base,
size_t nmemb, size_t size,
int (*compar)(const void *, const void *));
void qsort(const void *base, size_t nmemb,
size_t size,
int (*compar)(const void *, const void *));
*/
int cmp_int(const int *a, const int *b){
return *a - *b;
}
int main(void) {
int i;
int array_int[NUM] = {4, 56, 32, 2, 67, 43, 51};
qsort(array_int, NUM, sizeof(int), cmp_int);
for(i = 0; i < NUM; i++)
printf("%d ", array_int[i]);
putchar('\n');
int key = 62; //why no response in case of "int *key?"
int *value = (int*) bsearch(&key, array_int, NUM, sizeof(int),cmp_int);
if(value == NULL)
printf("The key is not found\n");
else
printf("value is : %d", *value);
//===============================
char array_str[NUM][NUM*10] = {"Shanghai", "Changsha", "Shenzhen", "Guangzhou",
"Nanjing", "Xian", "Hangzhou" };
char *array_str2[NUM] = {"Shanghai2", "Changsha", "Shenzhen", "Guangzhou",
"Nanjing", "Xian", "Hangzhou" }; //no response
qsort(array_str, NUM, NUM*10, strcmp);
for(i = 0; i < NUM; i++)
printf("%s ", array_str[i]);
putchar('\n');
char *str_key = "Shanghai";
char *str_find = (char*) bsearch(str_key, array_str, NUM, NUM*10, strcmp);
if(str_find == NULL)
printf("The str_key is not found\n");
else
printf("str_key is : %s", str_find);
return EXIT_SUCCESS;
}
qsort and qsearch
最新推荐文章于 2022-12-14 10:23:03 发布