快速排序:
#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;
}
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;
}
新聞熱點
疑難解答
圖片精選