#pragma once #include<vector> #include<algorithm> #include<string> #include<sstream> //stringstream #include<iomanip> //setw setfill //内置变量pass-by-value more than pass-by-reference ? //P12 --Effective C++(Chinese) //d位数,A数字 int get_d(const std::vector<int>& A) { int max = *std::max_element(A.cbegin(), A.cend()); int d = 0; for (int i = max; i != 0;d++) { i /= 10; } return d; } int get_ws(const std::vector<int>& A, int j,int ws) { int d = get_d(A); auto s = std::to_string(A[j]); std::stringstream ss; ss << std::left << std::setfill('0') << std::setw(d + 1) << s; s = ss.str(); ss << std::right << std::setfill(' '); int k = s[ws] - '0'; return k; } //k:A数组中最大值,ws: 对A的的第几位排序 A[ws] void Count_sort_wz(std::vector<int>& A, int ws) { // ws = pow(10, ws); std::vector<int> c(10); for (int j = 0;j != A.size();++j) ++c[get_ws(A,j,ws)]; for (int i = 1;i <= 10;++i) c[i] += c[i - 1]; std::vector<int> b(A.size()); for (int i = A.size() - 1;i >= 0;--i) b[--c[get_ws(A,i,ws)]] = A[i]; for (int i = 0; i != A.size();++i) A[i] = b[i]; } void Radix_Sort(std::vector<int>& A) { int max = *std::max_element(A.cbegin(), A.cend()); int d = get_d(A); for (int ws = 0;ws != d; ++ws) { //max 这时为0 Count_sort_wz(A, ws); } }
参考