一、桶排序介绍
桶排序(Bucket Sort)的原理很简单,它是将数组分到有限数量的桶子里。
假设待排序的数组a中共有N个整数,并且已知数组a中数据的范围[0, MAX)。在桶排序时,创建容量为MAX的桶数组r,并将桶数组元素都初始化为0;将容量为MAX的桶数组中的每一个单元都看作一个"桶"。
在排序时,逐个遍历数组a,将数组a的值,作为"桶数组r"的下标。当a中数据被读取时,就将桶的值加1。例如,读取到数组a[3]=5,则将r[5]的值+1。
二、桶排序图文说明
桶排序代码
1 /* 2 * 桶排序 3 * 4 * 参数说明: 5 * a -- 待排序数组 6 * n -- 数组a的长度 7 * max -- 数组a中最大值的范围 8 */ 9 void bucketSort(int a[], int n, int max) 10 { 11 int i,j; 12 int buckets[max]; 13 14 // 将buckets中的所有数据都初始化为0。 15 memset(buckets, 0, max*sizeof(int)); 16 17 // 1. 计数 18 for(i = 0; i < n; i++) 19 buckets[a[i]]++; 20 21 // 2. 排序 22 for (i = 0, j = 0; i < max; i++) 23 { 24 while( (buckets[i]--) >0 ) 25 a[j++] = i; 26 } 27 }
bucketSort(a, n, max)是作用是对数组a进行桶排序,n是数组a的长度,max是数组中最大元素所属的范围[0,max)。
假设a={8,2,3,4,3,6,6,3,9}, max=10。此时,将数组a的所有数据都放到需要为0-9的桶中。如下图:
在将数据放到桶中之后,再通过一定的算法,将桶中的数据提出出来并转换成有序数组。就得到我们想要的结果了。
三、桶排序的C++实现
1 /** 2 * 桶排序:C++ 3 * 4 * @author skywang 5 * @date 2014/03/13 6 */ 7 8 #include <iostream> 9 #include <cstring> 10 using namespace std; 11 12 /* 13 * 桶排序 14 * 15 * 参数说明: 16 * a -- 待排序数组 17 * n -- 数组a的长度 18 * max -- 数组a中最大值的范围 19 */ 20 void bucketSort(int* a, int n, int max) 21 { 22 int i, j; 23 int *buckets; 24 25 if (a==NULL || n<1 || max<1) 26 return ; 27 28 // 创建一个容量为max的数组buckets,并且将buckets中的所有数据都初始化为0。 29 if ((buckets = new int[max])==NULL) 30 return ; 31 memset(buckets, 0, max*sizeof(int)); 32 33 // 1. 计数 34 for(i = 0; i < n; i++) 35 buckets[a[i]]++; 36 37 // 2. 排序 38 for (i = 0, j = 0; i < max; i++) 39 while( (buckets[i]--) >0 ) 40 a[j++] = i; 41 42 delete[] buckets; 43 } 44 45 46 int main() 47 { 48 int i; 49 int a[] = {8,2,3,4,3,6,6,3,9}; 50 int ilen = (sizeof(a)) / (sizeof(a[0])); 51 52 cout << "before sort:"; 53 for (i=0; i<ilen; i++) 54 cout << a[i] << " "; 55 cout << endl; 56 57 bucketSort(a, ilen, 10); // 桶排序 58 59 cout << "after sort:"; 60 for (i=0; i<ilen; i++) 61 cout << a[i] << " "; 62 cout << endl; 63 64 return 0; 65 }