桶排序

1. 定义:
      桶排序(Bucket Sort)的基本思想是:将输入数据均匀地分配到有限数量的桶中,然后对每个桶再分别进行内部排序,最后按顺序将每个桶中的数据有序的组合起来。
 
2. C++程序:
#include <iostream>
#include <vector>
using namespace std;

typedef struct node
{
    int data;
    node *next;    
}Node;

int hashIndex(int val)
{
    return val/10;
}

vector<int> BucketSort(vector<int> array, int bucketsize)
{
    int len = array.size();
    vector<node *> bucket;
    bucket.reserve(bucketsize);
    /*初始化带头节点*/
    for(int i=0; i<bucketsize; ++i)
    {
        bucket[i] = new node;
        bucket[i]->next = NULL;
    }    
    /*将所有元素入桶并在桶内排序*/
    for(int i=0; i<len; ++i)
    {
        int index = hashIndex(array[i]);
        node *newnode = new node;
        newnode->data = array[i];
        newnode->next = NULL;
        node *p = bucket[index];
        if(p->next == NULL)
            p->next = newnode;
        else
        {
            while(p->next!=NULL && p->next->data <= newnode->data)
                p = p->next;
            newnode->next = p->next;
            p->next = newnode;
        }
    }
    /*合并N个桶*/
    int num = 0;
    vector<int> res;
    for(int i=0; i<bucketsize; ++i)
    {
        node *p = bucket[i]->next;
        while(p != NULL)
        {
            num++;
            res.push_back(p->data);
            p = p->next;    
        }    
    }
    /*释放所有节点资源*/
    for(int i=0; i<bucketsize; ++i)
    {
        node *p = bucket[i];
        while(p!=NULL)
        {
            node *tmp = p;
            p = p->next;
            delete tmp;     
        }
    }
    return res;
}

int main()
{
    cout<<"<======================Before Sort=======================>"<<endl;
    vector<int> vi= {15, 90, 25, 76, 47, 58, 32, 67, 84, 26, 12, 3, 9, 56,  
            98, 51, 79, 47, 39, 67 };
   for(auto &i :vi)
        cout<<i<<" ";
    cout<<endl;
    vector<int> res = BucketSort(vi,10);
    cout<<"<======================After Sort=======================>"<<endl;
    for(auto &i:res)
        cout<<i<<" ";
    cout<<endl;
    return 0;
}
运行结果如下:
原文地址:https://www.cnblogs.com/ladawn/p/8467944.html