// 二分查找法 #include <iostream> #include <vector> using namespace std; int BinarySearch(vector<int> vec,int target) { // 特殊输入 if(vec.size() <= 0) return -1; // 二分查找(非递归) int low = 0; int mid = 0; int high = vec.size()-1; // 注意:取等号 while(low <= high) { mid = (low + high)/2; if(vec[mid] == target) return mid; if(vec[mid] > target) high = mid-1; else low = mid+1; } return -1; } int main() { vector<int> vec = {1,2,3,5,7,7,7,7,9,10}; int target; while(cin>>target) cout<<BinarySearch(vec,target)<<endl; return 0; }
原文地址:https://www.cnblogs.com/wanglei5205/p/9384394.html
时间: 2024-11-09 18:33:18