zoukankan      html  css  js  c++  java
  • [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
  • 相关阅读:
    电池的并联与串联
    [转]为什么我会认为SAP是世界上最好用最牛逼的ERP系统,没有之一?
    go module
    thinkPHP5.1自动生成目录结构
    java多线程-锁分析
    Walle 2.0(瓦力)的安装
    轻量日志系统Loki
    Zabbix5.0的安装(超详细)
    政策制定的艺术
    浅谈对golang中的defer,panic,recover理解
  • 原文地址:https://www.cnblogs.com/jcliBlogger/p/4563731.html
Copyright © 2011-2022 走看看