C语言标准库的快排和二分查找

抽时间再详细把C语言标准头文件(库文件)梳理一下。

对于快速排序和二分查找,其实在C语言中有相应的实现,在头文件<stdlib.h>中,重点是实现cmp函数,以及理解它内部如何运作的。下面贴出代码:

/**
 * author:		CofCai
 * datatime:	2020-12-02 11:20:25
 * file description:
 *	 该文件是在搜索C语言标准头文件时,发现在<stdlib.h>中有
 *	 二分查找和快速排序的函数,所以遂研究以下。
 *	 二分查找:
 *	 void *bsearch(const void *key, const void *base, size_t n, size_t size, int (*cmp)(const void *keyval, const void *datum));
 *	 快速排序:
 *	 void qsort(void *base, size_t n, size_t size, int (*cmp)(const void *, const void *));
 *	 重点是实现cmp函数,n是base的个数,size是base中每个元素的大小,cmp是对base元素进行操作的函数指针。
 */


#include <stdio.h>
#include <string.h>
#include <stdlib.h>

void SortAndSearchStringEg();
void SortAndSearchNumEg();

int main(int argc, char const *argv[])
{
	SortAndSearchStringEg();
	SortAndSearchNumEg();
	return 0;
}


#define TYPE float

int cmp4num(const void* x, const void* y)
{
	TYPE a, b;
	a = *(TYPE*)x;
	b = *(TYPE*)y;
	if (a > b)			return 1;
	else if (a == b)	return 0;
	else				return -1;
}

void SortAndSearchNumEg()
{
	TYPE data[] = {10, 18, 2, 83, 82, 892, 23};
	TYPE target = 23;
	TYPE* get;
	printf("before quick sort:\n");
	for (int i = 0; i < sizeof(data)/sizeof(TYPE); ++i)
	{
		printf("%.f\n", data[i]);
	}
	qsort((void*)data, sizeof(data)/sizeof(TYPE), sizeof(TYPE), cmp4num);
	printf("after quick sort:\n");
	for (int i = 0; i < sizeof(data)/sizeof(TYPE); ++i)
	{
		printf("%.f\n", data[i]);
	}
	get = (TYPE*)bsearch((void*)&target, (void*)data, sizeof(data)/sizeof(TYPE), sizeof(TYPE), cmp4num);
	if (get != NULL) {
		printf("find value %f\n", *get);
	} else {
		printf("can't find value %f\n", target);
	}
}


int cmp4str(const void* x, const void* y)
{
	char* str1, *str2;
	str1 = (char*)x;
	str2 = (char*)y;
	return strncmp(str1, str2, sizeof(str1));	//升序
	// return -strncmp(str1, str2, sizeof(str1));	//降序
}

#define M 6
#define N 10

void SortAndSearchStringEg()
{
	char str[M][N] = {
		"hello",
		"name",
		"cofcai",
		"jackChen",
		"bruceLi",
		"shaby"
	};
	char* strtarget = "hh";
	char* strfind;
	printf("before sort:\n");
	for (int i = 0; i < M; ++i)
	{
		printf("str[%d] is: %s\n", i, str[i]);
	}
	/** 快速排序 */
	qsort(str, sizeof(str)/(sizeof(char)*N), sizeof(char)*N, cmp4str);
	printf("after sort:\n");
	for (int i = 0; i < M; ++i)
	{
		printf("str[%d] is: %s\n", i, str[i]);
	}
	/** 二分查找 */
	strfind = (char*)bsearch((const void*)strtarget, str, sizeof(str)/(sizeof(char)*N), sizeof(char)*N, cmp4str);
	if (strfind != NULL) {
		printf("find str: %s\n", strfind);
	} else {
		printf("don't find target str: %s\n", strtarget);
	}
}

结果如下:

赞赏