C语言使用stdlib.h库函数的二分查找和快速排序的实现代码
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#define LENGTH(x) sizeof(x)/sizeof(x[0])
/**输出数组元素
*\param arr:指向数组的指针
*\param len:数组元素的个数
*/
void print(char (*arr)[10],int len)
{
int i;
for (i=0;i<len;i++)
{
printf("%s ",arr[i]);
}
printf("\n");
}
int main()
{
char arr[][10]={"bac","bca","abc","acb","cba","cab"}; /* 定义二维字符数组*/
char *key="bca";/* 要查找的字符串*/
char *ptr=NULL; /* 字符指针*/
// 输出未排序时字符数组的内容
printf("before qsort :");
print(arr,LENGTH(arr));
/* 使用qsort对字符数组排序*/
qsort((void *)arr,LENGTH(arr),sizeof(arr[0]),(int (*)(const void *,const void *))strcmp);
/* 输出排序后字符数组的内容*/
printf("after qsort :");
print(arr,LENGTH(arr));
/* 采用二分查找查找指定字符*/
ptr=(char *)bsearch(key,arr,LENGTH(arr),sizeof(arr[0]),(int (*)(const void *,const void *))strcmp);
if(ptr)
{
/* 找到*/
printf("%s is in the array\n",key);
}
else/* 没找到*/
{
printf("%s isn't in the array\n",key);
}
return 0;
}
#include<stdlib.h>
#include<stdio.h>
#define ArrayLen(arr) (sizeof(arr) / sizeof(arr[0]))
int numarray[] = {123, 145, 512, 627, 800, 933};
int numeric (const int *p1, const int *p2)
{
return(*p1 - *p2);
}
int* lookup(int key)
{//返回值是指向key的地址
int *itemptr;
// The cast of (int(*)(const void *,const void*)) is needed to avoid a type mismatch error at
// compile time
itemptr = (int *)bsearch(&key, numarray, ArrayLen(numarray), \
sizeof(int), (int(*)(const void *,const void *))numeric);
return (itemptr);
}
int main(void)
{
int *p = lookup(512);
if(NULL != p)
printf("找到的key是%d,", *p);
printf("key的下标是%d\n", (p - numarray));
return 0;
}