template <typename T>
int binSearch(const T arr[], int first, int last, const T& target)
{
int mid; // index of the midpoint
T midValue; // object that is assigned arr[mid]
int origLast = last; // save original value of last
while (first < last) // test for nonempty sublist
{
mid = (first+last)/2;
midValue = arr[mid];
if (target == midValue)
return mid; // have a match
// determine which sublist to search
else if (target < midValue)
last = mid; // search lower sublist. reset last
else
first = mid+1; // search upper sublist. reset first
}
return origLast; // target not found
}
博客给出了一个二分查找算法的代码实现。该函数使用模板类型,接收数组、起始和结束索引以及目标对象作为参数,通过不断缩小查找范围,最终返回目标对象的索引或原结束索引表示未找到。
2094

被折叠的 条评论
为什么被折叠?



