• [Algorithms] Counting Sort


    Counting sort is a linear time sorting algorithm. It is used when all the numbers fall in a fixed range. Then it counts the appearances of each number and simply rewrites the original array. For a nice introduction to counting sort, please refer to Introduction to Alogrithms, 3rd edition. The following code is basically a translation of the pseudo code there.

     1 #include <iostream>
     2 #include <vector>
     3 #include <ctime>
     4 
     5 using namespace std;
     6 
     7 // Counting Sort an Array with each element in [0, upper]
     8 void countingSort(vector<int>& nums, int upper) {
     9     vector<int> counts(upper + 1, 0);
    10     for (int i = 0; i < (int)nums.size(); i++)
    11         counts[nums[i]]++;
    12     for (int i = 1; i <= upper; i++)
    13         counts[i] += counts[i - 1];
    14     vector<int> sorted(nums.size());
    15     for (int i = (int)nums.size() - 1; i >= 0; i--) {
    16         sorted[counts[nums[i]] - 1] = nums[i];
    17         counts[nums[i]]--;
    18     }
    19     swap(nums, sorted);
    20 }
    21 
    22 void print(vector<int>& nums) {
    23     for (int i = 0; i < (int)nums.size(); i++)
    24         printf("%d ", nums[i]);
    25     printf("
    ");
    26 }
    27 
    28 void countingSortTest(int len, int upper) {
    29     vector<int> nums(len);
    30     srand((unsigned)time(NULL));
    31     for (int i = 0; i < len; i++)
    32         nums[i] = rand() % (upper + 1);
    33     print(nums);
    34     countingSort(nums, upper);
    35     print(nums);
    36 }
    37 
    38 int main(void) {
    39     countingSortTest(20, 5);
    40     system("pause");
    41     return 0;
    42 }

    If you run this program, you are expected to see (I run it on Microsoft Visual Studio Professional 2012):

    2 3 4 1 5 1 1 5 4 0 3 2 2 5 5 3 5 5 3 4
    0 1 1 1 2 2 2 3 3 3 3 4 4 4 5 5 5 5 5 5
  • 相关阅读:
    CodeForces 1096E: The Top Scorer
    洛谷 P4175: bzoj 1146: [CTSC2008]网络管理
    洛谷 P4592: bzoj 5338: [TJOI2018]异或
    洛谷 P3307: bzoj 3202: [SDOI2013] 项链
    洛谷 P4248: bzoj 3238: [AHOI2013]差异
    洛谷 P5089: CodeForces #500 (Div. 1) B / 1012B : Chemical table
    关于Green-Kubo方法模拟水的粘度
    Lammps 关于初始化速度的分布问题
    LAMMPS-special bonds
    DL_POLY的安装问题
  • 原文地址:https://www.cnblogs.com/jcliBlogger/p/4563731.html
Copyright © 2020-2023  润新知