二分法查找
二分法查找是不是要求数据是递增的。如,(11,12,45,78,79,79,79,79,111,145,258,269,369,358,358,358,478)
要使用二分查找79和358,该怎么办。
void * binary_search(const void * value, const void * data, unsigned count, unsigned size, int (* compare)(const void *, const void *)) { unsigned start = 0, stop = count - 1; unsigned middle = (start + stop) / 2; while(compare(data + middle * size, value) && start < stop) { if(compare(data + middle * size, value) > 0) stop = middle - 1; else start = middle + 1; middle = (start + stop) / 2; } return !compare(data + middle * size, value) ? (void *)(data + middle * size): NULL; }