#include<iostream>
#include<vector>
#include<stdlib.h>
#include <cstring>
using namespace std;
void CountSort(int A[],int n=10)
{
int max = A[0], min = A[0]; //find max,min
for (int i = 0; i < n; ++i)
{
if (A[i]>max)
max = A[i];
if (A[i] < min)
min = A[i];
}
int range = max - min + 1; //get the length of B
int *B = new int[range]; //create B array
memset(B, 0, sizeof(int)*range);
for (int i = 0; i < n; ++i)
{
int pose=A[i]-min;
B[pose]++;
}
int j = 0;
for (int i = 0; i < range; ++i)
{
while(B[i]!=0)
{
A[j]=i+min;
B[i]--;
j++;
}
}
delete[] B;
}
int main() //test
{
int A[100] = { 0 };
for(int i=0;i<100;i++)
A[i]=((rand()%200)-100); //生成100个范围在【-100,100】内的随机数
cout << endl<<"Before CountSort A= ";
for (int i = 0; i < 100; ++i)
{
if (i == 0)
cout << "[ ";
cout << A[i];
if (i != 99)
cout << ",";
if (i == 99)
cout << " ]";
}
CountSort(A,100);
cout << endl<<"After CountSort A= ";
for (int i = 0; i < 100; ++i)
{
if (i == 0)
cout << "[ ";
cout << A[i];
if (i != 99)
cout << ",";
if (i == 99)
cout << " ]";
}
return 0;
}
01-19
04-17
06-08