木桶排序

木桶排序(箱排序)就是将数组中的数分到有限个木桶中去。木桶排序的必要步骤是计数,记录每一个数出现的次数。

原理图展示:

 我们先假设待排数组是a,数组长度为n,max代表数组中最大的数所在的范围,即[ 0,max)。木桶数组为buceks。

看上面的图,我们可以看到,在循环的时候,buckes[a[ i ]]++。这样就统计了每个数在a数组中出现的次数,并记录在了木桶数组中的相应位置。

我们计数之后,就要进行排序,排序我们就只需要遍历木桶数组,只要木桶数组的元素不为0,那么就代表这个数出现过。并且木桶数组的下标就是就是这个数,

木桶数组对应下标的值就是这个元素出现的次数。

代码:

#include<iostream>
#include<cstring>
using namespace std;
void bucket_sort(int a[],int n,int max)//a代表待排数组,n代表数组的最大长度,max代表数组中的最大值所在的范围。 
{
    int i=0,j=0;
    int buckets[max];//木桶数组 
    memset(buckets,0,sizeof(buckets));//将木桶数组中的每一个元素初始化为0,方便计数。 
    for(int i=0;i<n;i++)
          buckets[a[i]]++;//统计每个元素在在数组a中出现的次数 
    for(i=0;i<max;i++)
    {
        while(buckets[i]!=0)//排序 
        {
            a[j]=i;
            j++; 
            buckets[i]--;
        }
    }
 } 
int main()
{
    int n;
    cin>>n;
    int A[n];
    int max=0;
    for(int i=0;i<n;i++)
    {
        cin>>A[i];
        if(A[i]>max) max=A[i];
    }
    bucket_sort(A,n,max+1);
    for(int i=0;i<n;i++)
      cout<<A[i]<<" ";
      return 0;
}
原文地址:https://www.cnblogs.com/zhoubo123/p/11585475.html