《演算法導論》中的計數排序的C++實現
阿新 • • 發佈:2019-01-30
#include<iostream> #include<vector> using namespace std; void CountSort(vector<int> A, vector<int> &B, int k,int n) { int i,j; vector<int> C(k+1, 0); for (i = 0; i < n; i++) C[A[i]] = C[A[i]] + 1; for (j = 1; j <= k; j++) C[j] = C[j] + C[j - 1]; for (j = n-1; j >= 0; j--) { B[C[A[j]]] = A[j]; C[A[j]] = C[A[j]] - 1; } } int main(void) { vector<int> A = { 2, 5, 3, 0, 2, 3, 0, 3 }; vector<int> B(9, 0); //預留空間大一點,防止邊界溢位 因為C[A[j]]不會為0 B從1下標開始 CountSort(A, B, 6, 8); for (auto i = 1; i < 9;i++) cout <<B[i] << " "; cout << endl; return 0; }