第一个函数直接在原数组上排序
第二个函数不改动原有的数组,会生成新数组并返回
void countSort(int* a, int len) {
if (a == nullptr || !len)return;
int min = a[0], max = a[0];
for (int i = 1; i < len; i++) {
if (a[i] > max)max = a[i];
else if (a[i] < min)min = a[i];
}
int* cnt = new int[max - min + 1]{0};
for (int i = 0; i < len; i++) cnt[a[i] - min]++;
for (int i = 0, j = min; i < len && j <= max; j++) {
for (int k = cnt[j - min]; k > 0; k--)a[i++] = j;
}
delete[] cnt;
}
int* countSort2(int* a, int len) {
if (a == nullptr || !len)return nullptr;
int min = a[0], max = a[0];
for (int i = 1; i < len; i++) {
if (a[i] > max)max = a[i];
else if (a[i] < min)min = a[i];
}
int* cnt = new int[max - min + 1]{ 0 };
for (int i = 0; i < len; i++) cnt[a[i] - min]++;
for (int i = 0; i < max - min; i++)cnt[i + 1] += cnt[i];
int* temp = new int[len];
for (int i = len-1; i >= 0; i--) {
temp[cnt[a[i] - min] - 1] = a[i];
cnt[a[i] - min]--;
}
delete[] cnt;
return temp;
}
void test02() {
//sizeof(a) / sizeof(*a)
int a3[] = { 49,38,65,97,76,13,27,49 };
int a7[] = { 15,1,2,3,5,8,4,9,6,7 };
int a2[] = { 1,2,3,4,5,7,8,9,10,6 };
int a4[] = { 1,2,3,4,5,7,8,9,10,6 };
int a6[] = { 8,3,6,4,2,1,5,7,9,10,12,11 };
int a9[] = { 16,9,20,15,3,18,13,2,17,10,5,7,11,12,6,1,19,4,8,14 };
int a8[] = { 53,17,78,9,45,65,87,32 };
int a5[] = { 53, 3, 542, 748, 14, 214, 154, 63, 616 };
int a10[] = { 20,30,40,50,70,31,19,60 };
int a[] = { 1,3,7,14,8,5,11,17,13,6,12,20,23,26,4,19 };
int b[] = { 1,3,7,14,8,5,11,17,13,6,12,20,23,26,4,19 };
//qsort(a, sizeof(a) / sizeof(*a), sizeof(*a), [](const void* a, const void* b)->int {return *(int*)a - *(int*)b; });
//my_printAry(a, sizeof(a) / sizeof(*a));
int* temp=countSort2(b, sizeof(b) / sizeof(*b));
my_printAry(temp, sizeof(b) / sizeof(*b));
countSort(b, sizeof(b) / sizeof(*b));
my_printAry(b, sizeof(b) / sizeof(*b));
int cnt = 0;
for (int i = 0; i < sizeof(b) / sizeof(*b); i++)if (b[i] != temp[i])cnt++;
cout << cnt << endl;
delete[] temp;
}