Author🚹:CofCai
Email✉️:cai.dongjun@nexuslink.cn
QQ😙:1664866311
personal Page🏠
CSDN Page🏠
抽时间再详细把C语言标准头文件(库文件)梳理一下。
对于快速排序和二分查找,其实在C语言中有相应的实现,在头文件中,重点是实现cmp
函数,以及理解它内部如何运作的。下面贴出代码:
#include
#include
#include void SortAndSearchStringEg();
void SortAndSearchNumEg();int main(int argc, char const *argv[])
{SortAndSearchStringEg();SortAndSearchNumEg();return 0;
}#define TYPE floatint 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[] &#61; {10, 18, 2, 83, 82, 892, 23};TYPE target &#61; 23;TYPE* get;printf("before quick sort:\n");for (int i &#61; 0; i < sizeof(data)/sizeof(TYPE); &#43;&#43;i){printf("%.f\n", data[i]);}qsort((void*)data, sizeof(data)/sizeof(TYPE), sizeof(TYPE), cmp4num);printf("after quick sort:\n");for (int i &#61; 0; i < sizeof(data)/sizeof(TYPE); &#43;&#43;i){printf("%.f\n", data[i]);}get &#61; (TYPE*)bsearch((void*)&target, (void*)data, sizeof(data)/sizeof(TYPE), sizeof(TYPE), cmp4num);if (get !&#61; NULL) {printf("find value %f\n", *get);} else {printf("can&#39;t find value %f\n", target);}
}int cmp4str(const void* x, const void* y)
{char* str1, *str2;str1 &#61; (char*)x;str2 &#61; (char*)y;return strncmp(str1, str2, sizeof(str1));
}#define M 6
#define N 10void SortAndSearchStringEg()
{char str[M][N] &#61; {"hello","name","cofcai","jackChen","bruceLi","shaby"};char* strtarget &#61; "hh";char* strfind;printf("before sort:\n");for (int i &#61; 0; i < M; &#43;&#43;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 &#61; 0; i < M; &#43;&#43;i){printf("str[%d] is: %s\n", i, str[i]);}strfind &#61; (char*)bsearch((const void*)strtarget, str, sizeof(str)/(sizeof(char)*N), sizeof(char)*N, cmp4str);if (strfind !&#61; NULL) {printf("find str: %s\n", strfind);} else {printf("don&#39;t find target str: %s\n", strtarget);}
}
结果如下&#xff1a;