zoukankan      html  css  js  c++  java
  • 桶排序

    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;
    }
    运行结果如下:
  • 相关阅读:
    AC自动机+全概率+记忆化DP UVA 11468 Substring
    java POI技术之导出数据优化(15万条数据1分多钟)
    验证IP端与数据库Ip端是否重复!!!
    JAVA中IP和整数相互转化(含有掩码的计算)
    Nginx搭建反向代理服务器过程详解
    session原理及实现共享
    Linux部署多个tomcat
    linux下怎么修改mysql的字符集编码
    linux yum 安装mysql
    VM虚拟机下的Linux不能上网
  • 原文地址:https://www.cnblogs.com/ladawn/p/8467944.html
Copyright © 2011-2022 走看看