不断分段找中点,判断中点是否是要寻找的num 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455// 获取 num 在 vector 中的 indexint findIndex(const vector<int>& vector, int num);int main(int argc, char *argv[]){ vector<int> v; for(int i=0; i<9; i++) { v.emplace_back(); auto& num = v.back(); num = i*2; cout << " v.back: "<< v.back(); } int id = findIndex(v, 6) ; if(id < 0 ) cout << "no such number !" <<endl; else cout << "index of number is : "<< id <<endl; return 0;}int findIndex(const vector<int>& vector, int num){ Q_ASSERT(vector.size() >0 ); int size = vector.size(); if(vector.at(0) ==num ) return 0; if(size==1 && vector.at(0) !=num ) return -1; if(num == vector.back() ) return size-1; int begin, mid, end; begin =0; end = vector.size()-1; mid = (begin + end) / 2; int count = 0; while(num != vector.at(mid) ) { count++; if(count > log2(size) ) { return -1; break; } // 比较mid和num, 按情况只取一段进行递归比较,这样才降低复杂度 if( num > vector.at(mid) ) { begin = mid; end = end; mid = (begin + end) / 2; } else { begin = begin; end = mid; mid = (begin + end) / 2; } } return mid;}