桶式排序(bucket sort),是一种快速排序的算法。如果我们有N个整数,范围从1到M(或者是从0到M-1),对这N个整数进行排序。
(1)首先我们需要一个放置所有桶的数组bucketArray,数组长度为M+1,初始化每个单元为0。
(2)遍历N个整数,当读到i时,使bucketArray[i]加1。
(3)在所有数读完以后,扫描数组bucketArray,打印排序好的表。
第(1)步中数组长度可以替换为N个整数中最大数+1,因为这样既可以保证桶的数量足够,又可以在一定程度上节约空间。
具体实现如下(C++):
#include "stdafx.h"
#include "iostream"
using namespace std;
void bucket_sort(int *arr, int max, int size)
{
// 创建一个长度为“最大值+1”的数组 放置所有的桶
int *bucketArray = new int[max + 1]();
// 遍历初始数组 读入所有数据
for (int i = 0; i < size; i++)
{
bucketArray[arr[i]]++;
}
// 将排序好的数据输出
for (int i = 0; i < max+1; i++)
{
for (int j = 0; j < bucketArray[i]; j++)
{
cout << i << endl;
}
}
delete[] bucketArray;
}
int main()
{
// 初始数组
int arr[] = { 1,4,56,2,425,77,1 };
// 初始数组长度
int size = sizeof(arr) / sizeof(int);
// 数组中的最大值
int max = 425;
bucket_sort(arr, max, size);
return 0;
}
输出:
1
1
2
4
56
77
425
请按任意键继续. . .
不难看出,桶式排序的时间复杂度为O(n),但是当桶的数量比较大的时候是非常消耗空间的,可以说是一种牺牲空间换时间的算法。