Chinaunix首页 | 论坛 | 博客
  • 博客访问: 662181
  • 博文数量: 186
  • 博客积分: 1875
  • 博客等级: 上尉
  • 技术积分: 2117
  • 用 户 组: 普通用户
  • 注册时间: 2010-10-23 23:21
个人简介

有时候,就是想窥视一下不知道的东东,因为好奇!

文章分类

全部博文(186)

文章存档

2024年(2)

2023年(3)

2019年(1)

2018年(1)

2017年(2)

2016年(69)

2015年(53)

2014年(14)

2013年(1)

2012年(5)

2011年(25)

2010年(9)

分类: LINUX

2016-01-31 00:00:11

linux自带的qsort快速排序及bsearch二分查找接口. 

使用举例, 
  qsort1bsearch.c

点击(此处)折叠或打开

  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <string.h>

  4. struct mi {
  5.     int nr;
  6.     char *name;
  7. } months[] = {
  8.     { 1, "jan" }, { 2, "feb" }, { 3, "mar" }, { 4, "apr" },
  9.     { 5, "may" }, { 6, "jun" }, { 7, "jul" }, { 8, "aug" },
  10.     { 9, "sep" }, {10, "oct" }, {11, "nov" }, {12, "dec" }
  11. };

  12. #define nr_of_months (sizeof(months)/sizeof(months[0]))

  13. static int compmi(const void *m1, const void *m2)
  14. {
  15.     struct mi *mi1 = (struct mi *) m1;
  16.     struct mi *mi2 = (struct mi *) m2;
  17.     return strcmp(mi1->name, mi2->name);
  18. }

  19. int main(int argc, char **argv)
  20. {
  21.     int i;

  22.     qsort(months, nr_of_months, sizeof(struct mi), compmi);
  23.     for (i = 0; i < nr_of_months; i++) {
  24.         printf("%-4s\n", months[i].name);
  25.     }

  26.     printf("==============================================\n");
  27.     for (i = 1; i < argc; i++) {
  28.         struct mi key, *res;
  29.         key.name = argv[i];
  30.         res = bsearch(&key, months, nr_of_months, sizeof(struct mi), compmi);
  31.         if (res == NULL) {
  32.             printf("'%s': unknown month\n", argv[i]);
  33.         } else {
  34.             printf("%s: month #%d\n", res->name, res->nr);
  35.         }
  36.     }

  37.     exit(EXIT_SUCCESS);
  38. }
运行结果

先对数组months排序并打印结果. 再根据输入参数串查找并打印相应结构的另一元素,
阅读(1012) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~