排序算法:桶排序

桶排序的定義

先引用維基百科的一段話(huà)作為開(kāi)頭:

Bucket sort, or bin sort, is a sorting algorithm that works by distributing the elements of an array into a number of buckets. Each bucket is then sorted individually, either using a different sorting algorithm, or by recursively applying the bucket sorting algorithm.
from Wikipedia Bucket sort

我的理解

顧名思義,我們先擺好幾個(gè)桶,這幾個(gè)桶呢是按順序放好的,例如:0, 1, 2, 3 .... , 10;現(xiàn)在,我們有一組數(shù): 3, 5, 2, 1, 6, 4, 2, 8, 9,我們?cè)趺唇o這組數(shù)去排序呢?首先尋找一個(gè)標(biāo)桿,就是桶 (因?yàn)橥暗捻樞虻恼_的)。
然后我們把 3 扔進(jìn)桶 3, 5 扔進(jìn)桶 5,一次類(lèi)推,然后在將這些桶的數(shù)一一打印出來(lái)就可以了。從小到大,從大到小任君選擇。

Code

這里寫(xiě)一下 C code,僅作參考:

#include <stdio.h>

int main(){
    int a[11], i, j , t; // build 11 buckets
    for (i = 0; i < 10; i++)
        a[i] =0; // the initail values is zero
    
    for (i = 1; i <= 5; i++){ 
// the example has 5 numbers so i is less than 5 
        scanf("%d", &t);
        a[t]++;
    }
    
    for (i = 0; i <= 10; i++)
        for(j = 1; j <= a[i]; j++)
            printf("%d \n", i);
    getchar();
    
    return 0;
}

Reference:

https://en.wikipedia.org/wiki/Bucket_sort

《啊哈算法》 ISBN: 9787115354594

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容