• SCAU-8646基数排序C++


    Description

    用函数实现基数排序,并输出每次分配收集后排序的结果

    输入格式

    第一行:键盘输入待排序关键的个数n
    第二行:输入n个待排序关键字,用空格分隔数据

    输出格式

    每行输出每趟每次分配收集后排序的结果,数据之间用一个空格分隔

    输入样例

    10
    278 109 063 930 589 184 505 069 008 083

    输出样例

    930 063 083 184 505 278 008 109 589 069
    505 008 109 930 063 069 278 083 184 589
    008 063 069 083 109 184 278 505 589 930

    基数排序的基本思想
    将比较元素的各个关键值依次放入相应的“桶”中,再取出来,然后放入下一位的关键值,全部关键值放完之后排序完成。再比如说这道题目中的关键值是每个数字不同的位置上的值。在这里使用LSD(最次位优先排序)的方法进行排序,先将个位数上的值放入“桶”中,再依次取出来,然后再放十位数、百位数。

    解题思路
    由于题目中给出的数据的位数都是相同的,所以我直接选择了string来存储数据,使用下标读取不同位置的数值来将其放入对应的“桶”(在这里使用队列来作为桶)之中。

    #include <iostream>
    #include <cstring>
    #include <algorithm>
    #include <math.h>
    #include <cstdio>
    #include <string>
    #include <queue>
    typedef long long ll;
    const int MAXL=10000+10;
    
    using namespace std;
    
    
    int n;
    string a[MAXL];
    queue <string> bucket[10];
    
    void printarr()
    {
        int i;
        for(i=1; i<=n; i++)
        {
            cout<<a[i]<<" ";
        }
        cout<<endl;
    }
    
    
    void LSD()
    {
        int i,j,k;
        int max_len,temp;
        max_len=a[1].length();
    
        for(k=max_len-1;k>=0;k--)
        {
            for(i=1;i<=n;i++)
            {
                bucket[a[i][k]-48].push(a[i]);
            }
            for(i=0,j=1;i<10;i++)
            {
                while(!bucket[i].empty())
                {
                    a[j++]=bucket[i].front();
                    bucket[i].pop();
                }
            }
            printarr();
        }
    }
    
    
    int main()
    {
        cin>>n;
        for(int i=1; i<=n; i++)
        {
            cin>>a[i];
        }
        LSD();
    }
    
    
  • 相关阅读:
    python_linux系统相关配置
    python_字典dict相关操作
    python_传参
    mapreduce 学习笔记
    linux 常用命令
    C++ stringstream介绍,使用方法与例子
    C++/C++11中std::numeric_limits的使用
    C++中string erase函数的使用
    C++中accumulate的用法
    malloc的用法和意义
  • 原文地址:https://www.cnblogs.com/kstar/p/13100619.html
Copyright © 2020-2023  润新知