基数排序(桶排序)的C++实现

#include<iostream>
#include<vector>
#include<string>
using namespace std;


//低位优先
//测试数据   278 109 63 930 589 184 505 269 8 83
int main() {

    int n = 0;
    int max = 0;
    cout << "输入排序元素的个数:" << endl;
    cin >> n;
    vector<int>input(n);
    cout << "输入n个元素:" << endl;
    for (int i=0; i < n; i++) {
        cin >> input[i];
        if (input[i] > max)
            max = input[i];
    }
    string s = to_string(max);
    
    int flag = 1;
    for (int i = 0; i < s.length(); i++) {
        vector<vector<int>>bucket(10);
        for (int j = 0; j < n; j++) {
            int tmp = input[j];
            tmp = (tmp / flag) % 10;
            bucket[tmp].push_back(input[j]);
        }
        int t = 0;
        for (int j = 0; j < 10; j++) {
            for (int k = 0; k < bucket[j].size(); k++)
                input[t++] = bucket[j][k];
        }
        flag *= 10;
    }
    for (int i=0; i < n; i++)
        cout << input[i] << " ";
    return 0;
}

猜你喜欢

转载自blog.csdn.net/lannister_awalys_pay/article/details/85056988
今日推荐