#include<iostream>
#include<cmath> //pow used
using namespace std;
void ShowArray(int A[],int n)
{
cout << "result is :" << endl;
for (int i = 0; i < n ; i++)
cout << A[i] << " ";
cout << endl;
}
void CountingSort(int CpA[],int k,int n,int di) //k表示取值范围,此一位数0~9,n数组大小,di表示处理的第几位
{
//P109
int* C = new int[k + 1]; //dif
int *CopyA = new int[n]; //copyA
int* AA = new int[n];// 放A的某一位
for (int j = 0; j < n ; j++)
{
AA[j] =( CpA[j]/(int)pow(10.0,(double)(di - 1))) % 10; //这里也纠结了好久,忘了C++不能10^i了,而pow接受两个double ,而这里整除逻辑上不能用double,%用double本身就错
}
for (int i = 0 ; i < (k+1); i++) //dif
{
C[i] = 0;
}
for (int i = 0; i < n; i++)
{
C[AA[i]] = C[AA[i]] + 1; //统计某位数的个数和复制数组数据放一块执行
CopyA[i] = CpA[i];
}
for (int i = 1; i < (k + 1); i++)//dif
C[i] = C[i] + C[i-1];
for (int j = n - 1; j >= 0; j--)
{
CpA[C[AA[j]] - 1] = CopyA[j];//从n-1位置的数,放到其相应的位置,因为是重写,所以需要一个数组备份原数
C[AA[j]] = C[AA[j]] - 1;
}
delete[] C;
delete[] AA;
delete[] CopyA;
}
void RadixSort(int A[],int d, int n)
{
for (int i = 1; i <= d; i++)
{
CountingSort(A,10,n,i);
}
}
int main()
{
int A[10] = {162,411,120,124,127,419,163,112,128,161};
RadixSort(A,3,10);
ShowArray(A,10);
}
/*
如果未知位数,可加入检查最大数的最大位数函数
int MaxBit(int A[],int n)
{
int b = 1;
int max = 1;
for (int i = 0; i < n; i++)
{
int a = A[i];
while(0 != (a/10))
{
b++;
a = a/10;
}
if(b > max) max = b;
b = 1;
}
return max;
}
*/
#include<cmath> //pow used
using namespace std;
void ShowArray(int A[],int n)
{
cout << "result is :" << endl;
for (int i = 0; i < n ; i++)
cout << A[i] << " ";
cout << endl;
}
void CountingSort(int CpA[],int k,int n,int di) //k表示取值范围,此一位数0~9,n数组大小,di表示处理的第几位
{
//P109
int* C = new int[k + 1]; //dif
int *CopyA = new int[n]; //copyA
int* AA = new int[n];// 放A的某一位
for (int j = 0; j < n ; j++)
{
AA[j] =( CpA[j]/(int)pow(10.0,(double)(di - 1))) % 10; //这里也纠结了好久,忘了C++不能10^i了,而pow接受两个double ,而这里整除逻辑上不能用double,%用double本身就错
}
for (int i = 0 ; i < (k+1); i++) //dif
{
C[i] = 0;
}
for (int i = 0; i < n; i++)
{
C[AA[i]] = C[AA[i]] + 1; //统计某位数的个数和复制数组数据放一块执行
CopyA[i] = CpA[i];
}
for (int i = 1; i < (k + 1); i++)//dif
C[i] = C[i] + C[i-1];
for (int j = n - 1; j >= 0; j--)
{
CpA[C[AA[j]] - 1] = CopyA[j];//从n-1位置的数,放到其相应的位置,因为是重写,所以需要一个数组备份原数
C[AA[j]] = C[AA[j]] - 1;
}
delete[] C;
delete[] AA;
delete[] CopyA;
}
void RadixSort(int A[],int d, int n)
{
for (int i = 1; i <= d; i++)
{
CountingSort(A,10,n,i);
}
}
int main()
{
int A[10] = {162,411,120,124,127,419,163,112,128,161};
RadixSort(A,3,10);
ShowArray(A,10);
}
/*
如果未知位数,可加入检查最大数的最大位数函数
int MaxBit(int A[],int n)
{
int b = 1;
int max = 1;
for (int i = 0; i < n; i++)
{
int a = A[i];
while(0 != (a/10))
{
b++;
a = a/10;
}
if(b > max) max = b;
b = 1;
}
return max;
}
*/