您的位置:首页 > 其它

二分查找函数binary_search

2007-05-26 23:57 567 查看
函数模版:
template<typename T>
int binary_search (T arr[], int size, T target) ;

参数说明:
T: 模版参数
arr : 数组首地址,
size: 数组元素个数,
T target : 需要查找的值
返回值: 如果数组中找到target, 返回其下标
否则返回 -1
要求数组元素顺序非递减


template<typename T>


int binary_search (T arr[], int size, T target)




...{


int position;


T data;


int bottom = 0, top = size - 1;




while (bottom < top) ...{


int mid = (bottom + top) / 2;


data = arr[mid];


if (data < target)


bottom = mid + 1;


else


top = mid;


}


if (top < bottom) return -1;




else ...{


position = bottom;


data = arr[bottom];


if (data == target) return position;


else return -1;


}


}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: