二分查找函数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;
}
}
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;
}
}
相关文章推荐
- c++ 二分查找的函数 lower_bound & upper_bound & binary_search
- c++ 二分查找的函数 lower_bound & upper_bound & binary_search
- 笔试算法题(58):二分查找树性能分析(Binary Search Tree Performance Analysis)
- STL中的二分查找——lower_bound 、upper_bound 、binary_search
- STL中的二分查找(binary_search)
- (转)STL之二分查找(binary_search(),lower_bound(),upper_bound() )
- STL之二分查找 (Binary search in STL)
- 二分查找:binary_search、lower_bound和upper_bound的实现
- STL中的二分查找——lower_bound 、upper_bound 、binary_search
- STL之二分查找 (Binary search in STL)
- STL中的二分查找--lower_bound/upper_bound/binary_search
- Binary_search 二分查找
- STL之二分查找 (Binary search in STL)
- 二分查找树的C++实现 Binary Search Tree(BST)
- STL中的二分查找——lower_bound 、upper_bound 、binary_search
- 【转】STL之二分查找 (Binary search in STL)
- STL中的二分查找——lower_bound 、upper_bound 、binary_search
- STL中的二分查找——lower_bound 、upper_bound 、binary_search
- STL之二分查找(binary_search(),lower_bound(),upper_bound() )
- STL之二分查找 (Binary search in STL)