ALDS1_6_A: Counting Sort

题解
  1. 计数排序中需要设置一个以数组a元素范围为大小的中间数组c,c[i]的意义是“数组a中小于等于i的元素个数”。
  2. 排序的操作是新建一个数组b,然后在其c[a[i]]的位置放入元素a[i],放入后c[a[i]]–。
  3. 只要在排序中i是从后往前,计数排序就属于稳定的排序算法,时间复杂度为O(n+k),k是a中元素的范围大小。如果i从前往后,那么重复出现的元素将以逆序复制到b中。
  4. 为了方便以及考虑到计数排序的原理,这里a中的元素不能有负值,并且数组a和b要从1开始存储,而数组c从a的最小值存到a的最大值。
题目
Counting Sort
Counting sort can be used for sorting elements in an array which each of the n input elements is an integer in the range 0 to k. The idea of counting sort is to determine, for each input element x, the number of elements less than x as C[x]. This information can be used to place element x directly into its position in the output array B. This scheme must be modified to handle the situation in which several elements have the same value. Please see the following pseudocode for the detail:

Counting-Sort(A, B, k)
1    for i = 0 to k
2        do C[i] = 0
3    for j = 1 to length[A]
4        do C[A[j]] = C[A[j]]+1
5    /* C[i] now contains the number of elements equal to i */
6    for i = 1 to k
7    do C[i] = C[i] + C[i-1]
8    /* C[i] now contains the number of elements less than or equal to i */
9    for j = length[A] downto 1
10       do B[C[A[j]]] = A[j]
11          C[A[j]] = C[A[j]]-1

Write a program which sorts elements of given array ascending order based on the counting sort.

Input
The first line of the input includes an integer n, the number of elements in the sequence.

In the second line, n elements of the sequence are given separated by spaces characters.

Output
Print the sorted sequence. Two contiguous elements of the sequence should be separated by a space character.

Constraints
1 ≤ n ≤ 2,000,000
0 ≤ A[i]10,000

Sample Input 1
7
2 5 1 3 2 3 0

Sample Output 1
0 1 2 2 3 3 5
代码块
#include <iostream>
using namespace std;

int main(void)
{
    int i, n;
    cin>>n;
    int a[n];
    int c[10001];
    for(i=0; i<10001; i++)
        c[i] = 0;
    for(i=1; i<=n; i++)
    {
        cin>>a[i];
        c[a[i]]++;
    }
    for(i=1; i<10001; i++)
        c[i] += c[i-1];
    int b[n+1];
    for(i=n; i>=1; i--)
    {
        b[c[a[i]]] = a[i];
        c[a[i]]--;
    }
    for(i=1; i<=n; i++)
    {
        if(i!=n)
            cout<<b[i]<<' ';
        else
            cout<<b[i]<<endl;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值