#include<iostream>
#include"lei.h"
#include<cstdlib> // random 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 A[],int B[],int k,int n)
{
//P109
int* C = new int[k + 1]; //dif
for (int i = 0 ; i < (k+1); i++) //dif
C[i] = 0;
for (int j = 0; j < n ; j++)
C[A[j]] = C[A[j]] + 1;
for (int i = 1; i < (k + 1); i++)//dif
C[i] = C[i] + C[i-1];
for (int j = n - 1; j >= 0; j--)
{
B[C[A[j]] - 1] = A[j];
//这里阻碍了我好久,C[]计数个数是从1开始的,而B[]是从0开始的
C[A[j]] = C[A[j]] - 1;
}
delete[] C;
}
int main()
{
int A[10] = {16,4,10,14,7,9,3,2,8,1};
int B[10] = {};
CountingSort(A,B,20,10);
ShowArray(B,10);
}
#include"lei.h"
#include<cstdlib> // random 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 A[],int B[],int k,int n)
{
//P109
int* C = new int[k + 1]; //dif
for (int i = 0 ; i < (k+1); i++) //dif
C[i] = 0;
for (int j = 0; j < n ; j++)
C[A[j]] = C[A[j]] + 1;
for (int i = 1; i < (k + 1); i++)//dif
C[i] = C[i] + C[i-1];
for (int j = n - 1; j >= 0; j--)
{
B[C[A[j]] - 1] = A[j];
//这里阻碍了我好久,C[]计数个数是从1开始的,而B[]是从0开始的
C[A[j]] = C[A[j]] - 1;
}
delete[] C;
}
int main()
{
int A[10] = {16,4,10,14,7,9,3,2,8,1};
int B[10] = {};
CountingSort(A,B,20,10);
ShowArray(B,10);
}