#include<iostream>usingnamespace std;
constint N =10;
intmaxm(int arr[], int n) {
int max = arr[0];
for (int i =1; i < n; i++) {
if (arr[i] > max) {
max = arr[i];
}
}
return max;
}
intminm(int arr[], int n) {
int min = arr[0];
for (int i =1; i < n; i++) {
if (arr[i] < min) {
min = arr[i];
}
}
return min;
}
voidcountingSort(int arr[], int n) {
int min = minm(arr, n);
int max = maxm(arr, n);
int range = max - min +1;
int count[range] = {};
int output[n];
for (int i =0; i < n; i++) count[arr[i] - min]++;
for (int i =1; i < range; i++) count[i] += count[i -1];
for (int i = n -1; i >=0; i--) {
output[count[arr[i] - min] -1] = arr[i];
count[arr[i] - min]--;
}
for (int i =0; i < n; i++) arr[i] = output[i];
}
intmain() {
int n =7;
int arr[7] = {3, 5, 1, 1, 4, 2, 1};
cout <<"Input arr: ";
for (int i =0; i < n; i++) {
cout << arr[i] <<" ";
}
cout <<"\n";
countingSort(arr, n); // Sort elements in ascending order
cout <<"Output arr: ";
for (int i =0; i < n; i++) {
cout << arr[i] <<" ";
}
cout <<"\n";
}
此實現也適用於負數。
計數排序演算法的複雜度
時間複雜度
平均情況
計數排序對所有 n 項進行兩次迭代,對計數陣列進行一次迭代。因此,它的時間複雜度為 O(n+b),其中 b 是輸入的範圍。由於 b 通常較小,所以計數排序的時間複雜度可以說是 [Big Theta]:O(n)。
最壞情況
最壞情況下的時間複雜度為 [Big O]:O(n)。
最佳情況
最佳情況下的時間複雜度是 [Big Omega]:O(n)。它與最壞情況下的時間複雜度相同。
空間複雜度
計數排序演算法的空間複雜度為 O(n+b),其中 b 是輸入的範圍。它來自於 count&output 陣列。有時 b 可以比 n 大,但如果 b 小,時間複雜度可以說是 O(n)。
Harshit Jindal has done his Bachelors in Computer Science Engineering(2021) from DTU. He has always been a problem solver and now turned that into his profession. Currently working at M365 Cloud Security team(Torus) on Cloud Security Services and Datacenter Buildout Automation.