1 /** 2 * 排序算法之计数排序 3 **/ 4 #include <iostream> 5 #include <vector> 6 using namespace std; 7 8 void CountSort(vector<int> &arr, int maxVal) { 9 int len = arr.size(); 10 if (len < 1) 11 return; 12 vector<int> count(maxVal+1, 0); 13 vector<int> tmp(arr); 14 for (auto x : arr) 15 count[x]++; 16 for (int i = 1; i <= maxVal; ++i) 17 count[i] += count[i - 1]; 18 for (int i = len - 1; i >= 0; --i) { 19 arr[count[tmp[i]] - 1] = tmp[i]; 20 count[tmp[i]]--; //注意这里要减1 21 } 22 } 23 24 int main() 25 { 26 vector<int> arr = { 1,5,3,7,6,2,8,12,4,3,3 }; 27 int maxVal = 12; 28 CountSort(arr,maxVal); 29 for (auto x : arr) 30 cout << x << " "; 31 cout << endl; 32 return 0; 33 }