演算法題:中位元計算

來源:互聯網
上載者:User

中位元(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;            }        }    }}

一種為基本的演算法,另外一種為泛型的。排序後取中位元即可。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.