桶排序(基数排序)
//
// Created by Administrator on 2021/8/1.
//
#ifndef C__TEST01_RADIXSORTED_HPP
#define C__TEST01_RADIXSORTED_HPP
#include <iostream>
#include <vector>
#include <math.h>
using namespace std;
class RadixSorted {
public:
RadixSorted(vector<int> An);
static void radixSort(vector<int> &A);
static int maxBits(vector<int> &A);
static int getBits(int x, int d);
static void radixSort(vector<int> &A, int L, int R, int digit);
private:
vector<int> A;
};
RadixSorted::RadixSorted(vector<int> An) :
A(An){
A.resize(An.size());
}
int RadixSorted::maxBits(vector<int> &A) {
int max = INT_MIN;
for(int i = 0; i<A.size();++i){
if(A[i]>max){
max = A[i];
}
}
int res = 1;
while(max/10 !=0){
res++;
max /= 10;
}
return res;
}
int RadixSorted::getBits(int x, int d) {
return ((x/(int)(pow(10, d-1)))%10);
}
void RadixSorted::radixSort(vector<int> &A) {
if(A.empty() || A.size() == 1){
return;
}
radixSort(A, 0, A.size()-1, maxBits(A));
}
void RadixSorted::radixSort(vector<int> &A, int L, int R, int digit) {
int i, j;
vector<int> help(R-L+1);
//从个位开始遍历
for(int d = 1;d <= digit; ++d){
vector<int> count(10);
for(i = L; i < A.size(); ++i){
count[getBits(A[i], d)]++;
}
for(i = 1; i < 10; ++i){
count[i] += count[i-1];
}
for(j = R; j>=L; --j){
help[--count[getBits(A[j], d)]] = A[j];
}
}
for(i = L, j = 0; i<help.size(); ++i, ++j){
A[i] = help[j];
}
}
#endif //C__TEST01_RADIXSORTED_HPP
主要是给自己看的,所以肯定会出现很多错误哈哈哈哈哈