桶排序

存儲桶排序也稱為bin 排序。它的工作原理是將元素分配到也稱為存儲桶的數組中。 桶使用不同的排序演算法單獨排序。

桶排序的複雜性

演算法 複雜性
空間 O(1)
最壞情況 O(n^2)
最好情況 Ω(n+k)
平均情況 θ(n+k)

演算法

第1步,開始
第2步,設置一個最初為空的“桶”(`buckets`)數組。

第3步,分散:遍曆原始數組,將每個對象放入其存儲桶中。

第4步,對每個非空桶進行排序。

第5步,收集:按順序訪問存儲桶並將所有元素放回原始數組中。

第6步,停止

使用C語言實現桶排序演算法如下 -

#include <stdio.h>
void Bucket_Sort(int array[], int n)
{
    int i, j;
    int count[n];
    for (i = 0; i < n; i++)
        count[i] = 0;

    for (i = 0; i < n; i++)
        (count[array[i]])++;

    for (i = 0, j = 0; i < n; i++)
        for(; count[i] > 0; (count[i])--)
            array[j++] = i;
}
/* End of Bucket_Sort() */

/* The main() begins */
int main()
{
    int array[100], i, num;

    printf("Enter the size of array : ");
    scanf("%d", &num);
    printf("Enter the %d elements to be sorted:\n",num);
    for (i = 0; i < num; i++)
        scanf("%d", &array[i]);
    printf("The array of elements before sorting : \n");
    for (i = 0; i < num; i++)
        printf("%d ", array[i]);
    printf("The array of elements after sorting : \n");
    Bucket_Sort(array, num);
    for (i = 0; i < num; i++)
        printf("%d ", array[i]);
    printf("\n");
    return 0;
}

上一篇: 冒泡排序 下一篇: 梳排序