桶排序属于简单而且易于理解的排序算法,接下来介绍一下该算法的思想。
(1) 桶排序的思想
桶排序的思想就是:首先遍历一遍数组,找出数组中值最大的元素,假设最大的元素为Max;然后定义Max+1个“桶”,可以用“队列”或“栈”来定义;之后再遍历一遍数组,将元素值为i的元素放在第i个桶中;最后从第0个桶开始遍历,将桶中的元素依次放入原有数组中,直到遍历到第Max个桶为止。
由此可见,桶排序目的是以扩大内存空间为代价,从而减少时间复杂度。但是假若数组中的元素很少,而数组中值最大的元素非常大的时候,用这种算法显然也不能减少时间复杂度,故实际中很少用到这种排序算法。此外,对于浮点型的数据,这种算法就非常不适合,除非找到桶的下标(因为桶的下标为整型)与数值精度的映射关系。在桶排序的基础上,对该算法进行了改进,产生了“基数排序”,读者若是想了解“基数排序”思想,可以点击这里。
(2) 桶排序的实现
本次排序算法采用C++模版编程来实现。
#include <iostream>
#include <iterator>
#include <queue>
using std::cout;
using std::endl;
using std::ostream_iterator;
using std::queue;
template<class T,size_t N>
void PrintArr(T (&arr)[N])
{
copy(arr,arr+N,ostream_iterator<T>(cout," "));
cout << endl;
}
template<class T,size_t N>
void BucketSort(T (&arr)[N])
{
size_t i(0),j(0),max(arr[0]);
while(i < N) {
if(arr[i] > max) {
max = arr[i];
}
i++;
}
queue<T> buckets[max+1];
i = 0;
while(i < N) {
buckets[arr[i]].push(arr[i]);
i++;
}
i = 0;
while(i <= max) {
while(!buckets[i].empty()) {
arr[j] = buckets[i].front();
buckets[i].pop();
j++;
}
i++;
}
}
int main()
{
int arr[]= {2,1,5,3,2,6,1,1,8,4,7};
cout << "The init:" << endl;
PrintArr(arr);
cout << "The sort:" << endl;
BucketSort(arr);
PrintArr(arr);
cout << "The final:" << endl;
PrintArr(arr);
}
原始数组为:2 1 5 3 2 6 1 1 8 4 7
程序运行的结果为:1 1 1 2 2 3 4 5 6 7 8