?? mybinarysearch.c
字號:
/**
*
* @file MyBinarySearch.c 二分查找
*
* @author lin shao chuan (email:lsccsl@tom.com, msn:lsccsl@163.net)
*
*/
#include "MyAlgorithm.h"
#include <assert.h>
#include "myutility.h"
/**
* @brief 在一個有序序列里做二分查找
*/
static int __alg_binary_search(const void * buf, size_t len, size_t step_size,
const void * key,
ALG_COMPARE compare, size_t * pindex,
const void * context)
{
size_t hi = len;
size_t lo = 0;
assert(buf && len && step_size && compare);
while(hi > lo)
{
size_t mid = (hi + lo) / 2;
int ret = compare(key, GET_INDEX_PTR(buf, mid, step_size), context);
if(ret > 0)
{
lo = mid + 1;
continue;
}
else if(ret < 0)
{
hi = mid;
continue;
}
else
{
if(pindex)
*pindex = mid;
return 0;
}
}
assert(hi == lo);
if(pindex)
*pindex = lo;
return -1;
}
/**
*
* @brief 在一個有序序列里做二分查找
*
* @param buf:有序序列數據緩沖區起始地址
* @param len:有序序列中的元素個數
* @param step_size:每個元素的大小
* @param key:要查找的關鍵字
* @param compare:比較回調(不可為空)
* @param pindex:如果找到,返回元素的位置
*
* @retval 0:成功
* @retval 其它:失敗
*
*/
int MyBinarySearch(const void * buf, size_t len, size_t step_size,
const void * key,
ALG_COMPARE compare, size_t * pindex,
const void * context)
{
if(NULL == buf || 0 == len || 0 == step_size || NULL == compare)
return -1;
return __alg_binary_search(buf, len, step_size, key, compare, pindex, context);
}
?? 快捷鍵說明
復制代碼
Ctrl + C
搜索代碼
Ctrl + F
全屏模式
F11
切換主題
Ctrl + Shift + D
顯示快捷鍵
?
增大字號
Ctrl + =
減小字號
Ctrl + -