經典排序演算法 – 基數排序Radix sort

來源:互聯網
上載者:User

經典排序演算法 - 基數排序Radix sort

原理類似桶排序,這裡總是需要10個桶,多次使用

首先以個位元的值進行裝桶,即個位元為1則放入1號桶,為9則放入9號桶,暫時忽視十位元

例如

待排序數組[62,14,59,88,16]簡單點五個數字

分配10個桶,桶編號為0-9,以個位元數字為桶編號依次入桶,變成下邊這樣

|  0  |  0  | 62 |  0  | 14 |  0  | 16 |  0  |  88 | 59 |

|  0  |  1  |  2  |  3  |  4 |  5  |  6  |  7  |  8  |  9  |桶編號

將桶裡的數字順序取出來,

輸出結果:[62,14,16,88,59]

再次入桶,不過這次以十位元的數字為準,進入相應的桶,變成下邊這樣:

由於前邊做了個位元的排序,所以當十位元相等時,個位元字是由小到大的順序入桶的,就是說,入完桶還是有序

|  0  | 14,16 |  0  |  0  |  0  | 59 | 62  | 0  | 88  |  0  |

|  0  |  1      |  2  |  3  |  4  |  5  |  6  |  7  |  8  |  9  |桶編號


因為沒有大過100的數字,沒有百位元,所以到這排序完畢,順序取出即可

最後輸出結果:[14,16,59,62,88]

代碼僅供參考

        /// <summary>        /// 基數排序        /// 約定:待排數字中沒有0,如果某桶內數字為0則表示該桶未被使用,輸出時跳過即可/// </summary>        /// <param name="unsorted">待排數組</param>        /// <param name="array_x">桶數組第一維長度</param>        /// <param name="array_y">桶數組第二維長度</param>        static void radix_sort(int[] unsorted, int array_x = 10, int array_y = 100)        {            for (int i = 0; i < array_x/* 最大數字不超過999999999...(array_x個9) */; i++)            {                int[,] bucket = new int[array_x, array_y];                foreach (var item in unsorted)                {                    int temp = (item / (int)Math.Pow(10, i)) % 10;                    for (int l = 0; l < array_y; l++)                    {                        if (bucket[temp, l] == 0)                        {                            bucket[temp, l] = item;                            break;                        }                    }                }                for (int o = 0, x = 0; x < array_x; x++)                {                    for (int y = 0; y < array_y; y++)                    {                        if (bucket[x, y] == 0) continue;                        unsorted[o++] = bucket[x, y];                    }                }            }        }        static void Main(string[] args)        {            int[] x = { 999999999, 65, 24, 47, 13, 50, 92, 88, 66, 33, 22445, 10001, 624159, 624158, 624155501 };            radix_sort(x);            foreach (var item in x)            {                if (item > 0)                    Console.WriteLine(item + ",");            }            Console.ReadLine();        }

 

返回主目錄 [經典排序演算法][集錦]

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.