【算法】中位数 median

median 是 STL 内部的算法,用于求三个数的中位数,它将用于 std::sort, std::nth_element 的实现中,快速排序和求第 k 小数算法都用到了划分,选取 pivot 时为“三者取中”,即 *first, *(first + (last - first) / 2), *(last - 1) 三者的中位数,这两个算法后面会介绍。

median 的源码如下:

template 
inline const T & median(const T &a, const T &b, const T&c) {
	if (a < b) {
		if (b < c) {
			return b;
		} else if (a < c) {
			return c;
		} else {
			return a;
		}
	} else if (a < c) {
		return a;
	} else if (b < c) {
		return c;
	} else {
		return b;
	}
}
画成决策树的形式为

【算法】中位数 median_第1张图片





你可能感兴趣的:(Algorithms,Source,Code,STL,C/C++)