二分查找C++
返回类型为bool:
1 template<class T> static bool binarySearch(T *s, T const &e, int lo, int hi){ 2 while (lo < hi) { 3 int mi = (lo + hi) >> 1; 4 e < s[mi] ? hi = mi : lo = mi + 1; 5 } 6 return --lo == -1 ? false : s[lo] == e;//这个方法查找失败返回不大于e的秩 7 }
大师们的代码不仅简洁而且美观!
返回值不小于查找元素值的秩:
1 template<class T> static int binarySearch(T *s, T const &e, int lo, int hi){ 2 while (lo < hi) { 3 int mi = (lo + hi) >> 1; 4 e < s[mi] ? hi = mi : lo = mi + 1; 5 } 6 return --lo;//这个方法查找失败返回不大于e的秩 7 }
1 int upper_bound(int s[], int const& e, int lo, int hi) { 2 while (lo < hi) { 3 int mi = (lo + hi) >> 1; 4 e < s[mi] ? hi = mi : lo = mi + 1; // 将 e < s[mi] --> e <= s[mi]就是lower_bound 5 } 6 return lo; 7 }