Skip to content

Instantly share code, notes, and snippets.

@leftrk
Created December 4, 2018 16:53
Show Gist options
  • Select an option

  • Save leftrk/89b3bb2164bd03e4853d0b1b4084fcdf to your computer and use it in GitHub Desktop.

Select an option

Save leftrk/89b3bb2164bd03e4853d0b1b4084fcdf to your computer and use it in GitHub Desktop.
二分查找
template <typename Comparable>
int binarySearch(const vector<Comparable>& a, const Comparable& x) {
int low = 0, high = a.size() - 1;
while (low <= high) {
int mid = (low + high) / 2;
if (a[mid] < x)
low = mid + 1;
else(a[mid] > x)
high = mid - 1;
else
return mid;
}
return NOT_FOUND;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment