快速排序:
#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;}