标签:
ForwardIter lower_bound(ForwardIter first, ForwardIter last,const _Tp& val)算法返回一个非递减序列[first, last)中的第一个大于等于值val的位置。
ForwardIter upper_bound(ForwardIter first, ForwardIter last, const _Tp& val)算法返回一个非递减序列[first, last)中第一个大于val的位置。
lower_bound和upper_bound如下图所示:
1:lower_bound的源码
template <class _ForwardIter, class _Tp, class _Distance> _ForwardIter __lower_bound(_ForwardIter __first, _ForwardIter __last, const _Tp& __val, _Distance*) { _Distance __len = 0; distance(__first, __last, __len); _Distance __half; _ForwardIter __middle; while (__len > 0) { __half = __len >> 1; __middle = __first; advance(__middle, __half); if (*__middle < __val) { __first = __middle; ++__first; __len = __len - __half - 1; } else __len = __half; } return __first; }
int lower_bound(int *array, int size, int key) { int first = 0, middle; int half, len; len = size; while(len > 0) { half = len >> 1; middle = first + half; if(array[middle] < key) { first = middle + 1; len = len-half-1; //在右边子序列中查找 } else len = half; //在左边子序列(包含middle)中查找 } return first; }
int Lower_bound(int *a , int n , int value) { int left = 0; int right = n-1; while(left <= right) { int mid = (left + right)/2; if(a[mid] < value) { left = mid+1; } else right = mid -1; } return left; }
源码:
int upper_bound(int *array, int size, int key) { int first = 0, len = size-1; int half, middle; while(len > 0){ half = len >> 1; middle = first + half; if(array[middle] > key) //中位数大于key,在包含last的左半边序列中查找。 len = half; else{ first = middle + 1; //中位数小于等于key,在右半边序列中查找。 len = len - half - 1; } } return first; }
int Lower_bound(int *a , int n , int value) { int left = 0; int right = n-1; while(left <= right) { int mid = (left + right)/2; if(a[mid] <= value) { left = mid+1; } else right = mid -1; } return left; }
标签:
原文地址:http://blog.csdn.net/u013445530/article/details/46426809