經典排序演算法 – 桶排序Bucket sort

來源:互聯網
上載者:User

經典排序演算法 - 桶排序Bucket sort

補充說明三點

1,桶排序是穩定的

2,桶排序是常見排序裡最快的一種,比快排還要快…大多數情況下

3,桶排序非常快,但是同時也非常耗空間,基本上是最耗空間的一種排序演算法

我自己的理解哈,可能與網上說的有一些出入,大體都是同樣的原理

無序數組有個要求,就是成員隸屬於固定(有限的)的區間,如範圍為[0-9](考試分數為1-100等)

例如待排數字[6 2 4 1 5 9]

準備10個空桶,最大數個空桶

[6 2 4 1 5 9]           待排數組

[0 0 0 0 0 0 0 0 0 0]   空桶

[0 1 2 3 4 5 6 7 8 9]   桶編號(實際不存在)

 

1,順序從待排數組中取出數字,首先6被取出,然後把6入6號桶,這個過程類似這樣:空桶[ 待排數組[ 0 ] ] = 待排數組[ 0 ]

[6 2 4 1 5 9]           待排數組

[0 0 0 0 0 0 6 0 0 0]   空桶

[0 1 2 3 4 5 6 7 8 9]   桶編號(實際不存在)

 

2,順序從待排數組中取出下一個數字,此時2被取出,將其放入2號桶,是幾就放幾號桶

[6 2 4 1 5 9]           待排數組

[0 0 2 0 0 0 6 0 0 0]   空桶

[0 1 2 3 4 5 6 7 8 9]   桶編號(實際不存在)

 

3,4,5,6省略,過程一樣,全部入桶後變成下邊這樣

[6 2 4 1 5 9]           待排數組

[0 1 2 0 4 5 6 0 0 9]   空桶

[0 1 2 3 4 5 6 7 8 9]   桶編號(實際不存在)

 

0表示空桶,跳過,順序取出即可:1 2 4 5 6 9

以下代碼僅供參考

        /// <summary>        /// 桶排序        /// 1),已知其區間,例如[1..10],學生的分數[0...100]等        /// 2),如果有重複的數字,則需要 List<int>數組,這裡舉的例子沒有重複的數字        /// </summary>        /// <param name="unsorted">待排數組</param>        /// <param name="maxNumber">待排數組中的最大數,如果可以提供的話</param>        /// <returns></returns>        static int[] bucket_sort(int[] unsorted, int maxNumber = 99)        {            int[] sorted = new int[maxNumber + 1];            for (int i = 0; i < unsorted.Length; i++)            {                sorted[unsorted[i]] = unsorted[i];            }            return sorted;        }        static void Main(string[] args)        {            int[] x = { 99, 65, 24, 47, 50, 88,33, 66, 67, 31, 18 };            var sorted = bucket_sort(x, 99);            for (int i = 0; i < sorted.Length; i++)            {                if (sorted[i] > 0)                    Console.WriteLine(sorted[i]);            }            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.