任何使用比较的排序算法时间复杂度通常为O(N log N),但是在某些特殊情况下,以线性时间进行排序还是有可能的。
桶排序假设输入的数据均为小于M的正整数,然后声明一个大小为M的数组L,数组值均初始化为0,读取输入数据i,并执行L[i]++,则L数组中不为0的元素值的下标序列就是排序后的序列。
实现代码如下:
#include<iostream>
using namespace std;
void BucketSort(int input[], int n);
int main()
{
int input[10] = { 2, 0, 1, 7, 0, 1, 0, 1, 8, 1}; //示例代码取值较小
BucketSort(input, 10);
}
void BucketSort(int input[], int n)
{
int tmp[9] = {0, 0, 0, 0, 0, 0, 0, 0, 0};
for (int i = 0; i < n; i++)
tmp[input[i]]++;
for (int i = 0, j = 0; i < 9; i++)
while (tmp[i]--)
{
input[j] = i;
j++;
}
}