使用qsort()和bsearch()函数对值和字符串进行排序和查找

#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));
}


转载于:https://my.oschina.net/u/241930/blog/521930

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值