跳到正文

算法·理论

计数排序笔记

tangruicheng923约 2 分钟
原文
文章信息与版本

文章信息

发布
2025年10月12日
收录
2025年12月12日
更新
2026年10月29日
篇幅
约 2 分钟
获赞
1

版本

  1. v3当前
  2. v2
  3. v1

今天,老师让我们写了一道计数排序的题: 需要用数组记录数出现的次数,程序如下:

C++
#include<bits/stdc++.h>
using namespace std;
int main(){
    int a[1005]={0},n,i,c;
    cin>>n;
    for(i=0;i<n;i++){
        cin>>c;
        a[c]++;
    }
    for(int i=0;i<=1000;i++){
        if(a[i]!=0){
            cout<<i<<" "<<a[i]<<endl;
        }
    }
    return 0;
}

要运用到这个方法的还有直方图这题,题目自己去看,它只需要在原来的程序改一改,加一个判断最大值即可:

C++
#include<bits/stdc++.h>
using namespace std;
int main(){
    int a[10005]={0},n,Fmax,y;
    cin>>n;
    for(int i=1;i<=n;i++){
        cin>>y;
        a[y]++;
        if(a[y]>Fmax) Fmax=a[y];
    }
    for(int i=0;i<=Fmax;i++){
        cout<<a[i]<<endl;
    }
    return 0;
}

还有一种办法是用开挂函数sort这个函数可以快排数列,不过默认从小到大排序。

原文