C语言排序和搜索
所属分类 c
浏览量 773
void qsort(void *base, size_t num, size_t size, int (*compar)(const void*, const void*));
void *bsearch(const void *key, const void *base, size_t num, size_t size, int (*compar)(const void*, const void*));
qsort 对数组进行排序
base 数组,num为数组中元素数量,size为每个数组元素大小,compar为指向比较函数的指针
bsearch 二分查找有序数组
key 关键字
base 数组
num 数组中元素个数
size 每个数组元素的大小
compare 比较函数的指针
#include "stdio.h"
#include "stdlib.h"
int comp(const void* x, const void *y){
int *ix = (int *)x;
int *iy = (int *)y;
if (*ix > *iy)
return 1;
else if (*ix == *iy)
return 0;
else
return -1;
}
int main(){
int nums[] = {1,2,3,9,7,8};
int num = sizeof(nums) / sizeof(nums[0]);
printf("num=%d\n",num);
qsort(nums, num, sizeof(int), comp);
printf("sorted:");
int i = 0;
for (i = 0; i < num; i++){
printf("%d ", nums[i]);
}
printf("\n");
int k = 7;
int *findedItem = bsearch(&k, nums, num, sizeof(int), comp);
if (findedItem != NULL){
printf("%d exist in array \n", *findedItem);
}else{
printf("%d not exist in array\n", k);
}
k = 20;
findedItem = bsearch(&k, nums, num, sizeof(int), comp);
if (findedItem != NULL){
printf("%d exist in array \n", *findedItem);
}else{
printf("%d not exist in array\n", k);
}
return 0;
}
https://gitee.com/dyyx/hellocode/blob/master/web/tech/c/demo/stdlib/search_sort2.c
上一篇
下一篇
java 和 C 循环和递归性能比较
C++11 chrono 获取时间戳
C语言字符串转浮点数
C语言 rand srand rand_r
C语言动态内存分配与释放
exit atexit 及 abort