折半查找又成为二分查找,常用来对有序的线性表做元素查找。适用于一经建立,很少改变并且经常查找的场景。
实现如下:
/**
* Function binary_search (number, array, array_len)
*
* Returns
* -1,if not found.index of array,if found.
*
* Parameters
* @number: the nubmer waiting for search
* @array: search array pointer
* @array_len: esarch array len
*
* Description
* premise that array is orderly.
*
**/
static int binary_search(int number, int *array, int array_len)
{
int mid, start = 0, end = array_len - 1;
while (start <= end) {
mid = (start + end) / 2;
if (array[mid] < number)
start = mid + 1;
else if (array[mid] > number)
end = mid - 1;
else
return mid;
}
return -1;
}
使用二分思想,求平方根的函数:
/**
* Function mysqrt (y, precision)
*
* Returns
*
*
* Parameters
* @y:
* @precision:
*
* Description
* 求y的平方根,x*x == y
*
**/
static double mysqrt(double y, double precision)
{
double x, start = 0.0, end = y;
assert(y > 0.0);
while (1) {
x = (start + end) / 2;
if (x*x < y)
start = x;
else
end = x;
if (fabs(x*x - y) < precision)
break;
}
return x;
}
阅读(1668) | 评论(0) | 转发(0) |