qsort and qsearch

本文通过C语言实现了一个简单的排序程序,并使用了qsort函数进行数组排序,之后利用bsearch函数实现了二分查找。示例中包括整数数组和字符串数组的排序与查找过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值