折半查找函数模板:
#include <iostream>
using namespace std;
template <class T>
int binSearch(const T list[], int n, const T &key) {
int low = 0;
int high = n - 1;
while (low <= high) {
int mid = (low + high) / 2;
if (key == list[mid])
return mid;
else if (key < list[mid])
high = mid - 1;
else
low = mid + 1;
}
return -1;
}
int main() {
int a[5] = {3,4,5,6,7};
binSearch(a, 5, 4);
cout << binSearch(a, 5, 3);
return 0;
}
本人技术水平有限,若有错误或不当之处,可以在本号内反馈给我,一起交流一起学习!My WeChatID is 1958801919.
公众号底部二维码.jpeg
网友评论