#include <iostream>
#include <math.h>
using namespace std;
bool coutingSort(int array[], size_t arrLen)
{
if (arrLen < 2)
{
return true;
}
int max = array[0];
int min = array[0];
for (size_t i = 1; i < arrLen; ++i)
{
if (min > array[i])
{
min = array[i];
}
else if (max < array[i])
{
max = array[i];
}
}
int *countingBuckets = new int[max - min + 1]();
for (size_t j = 0; j < arrLen; ++j)
{
++countingBuckets[array[j] - min];
}
for (size_t k = 1; k < (max - min + 1); ++k)
{
countingBuckets[k] += countingBuckets[k-1];
}
int *tempArray = new int[arrLen]();
for (int l = arrLen - 1; l >= 0; --l)
{
tempArray[--countingBuckets[array[l] - min]] = array[l];
}
for (size_t m = 0; m < arrLen; ++m)
{
array[m] = tempArray[m];
}
delete [] countingBuckets;
delete [] tempArray;
return true;
}
void printArray(int array[], int arrLen)
{
for (int i = 0; i < arrLen; ++i)
{
cout << array[i] << " ";
}
cout << endl;
}
int main()
{
int a[]={11,9,20,56,42,3,7,15,16};
int arrayLen = sizeof(a)/sizeof(int);
cout<<"待排序的数 "<<endl;
printArray(a, arrayLen);
cout<<endl<<"排完序后:"<<endl;
coutingSort(a, arrayLen);
printArray(a, arrayLen);
cout<<endl<<"最小值为: "<<a[0]<<endl;
cout<<endl<<"最大值为: "<<a[arrayLen-1];
}