Welcome

首页 / 软件开发 / 数据结构与算法 / 算法题:中位数计算

算法题:中位数计算2013-11-14中位数(Median)

1、定义:一组数据按从小到大(或从大到小)的顺序依次排列,处在中间位置的一个数(或最中间两个数据的平均数,注意:和众数不同,中位数不一定在这组数据中)。

注:当个数为基数时,取最中间位置的数;当个数为偶数时,取最中间两个数的平均数。

2、从小到大排序,可以先用冒泡排序,然后取中位数,那么先看下冒泡排序算法,代码如下:

public static void BubbleSort(this IList<double> array){if (array == null || array.Count == 0){return;} int count = array.Count; for (int i = 0; i < count - 1; i++){for (int j = 0; j < count - i - 1; j++){if (array[j + 1] < array[j]){double temp = array[j + 1];array[j + 1] = array[j];array[j] = temp;}}}} public static void BubbleSort<T>(this IList<T> array) where T : IComparable{if (array == null || array.Count == 0){return;} int count = array.Count; for (int i = 0; i < count - 1; i++){for (int j = 0; j < count - i - 1; j++){if (array[j + 1].CompareTo(array[j]) < 0){T temp = array[j + 1];array[j + 1] = array[j];array[j] = temp;}}}}
一种为基本的算法,另外一种为泛型的。排序后取中位数即可。