中位元(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; } } }}
一種為基本的演算法,另外一種為泛型的。排序後取中位元即可。