You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1.2 KiB

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

计数排序

一、前置知识

C++求整数数组长度的办法

int len = sizeof(a) / sizeof(int);

二、算法步骤

  • 准备数组中 最大值那么多的桶,枚举每一个数字,发现一个数字,就将对应桶号中的个数加1

  • 从头开始枚举每个 有可能的桶,看看里面有几个计数,就打印几个当前的桶号。

三、算法动画

### 四、代码实现

#include <bits/stdc++.h>

using namespace std;
const int INF = 0x3f3f3f3f;
const int N = 1e6 + 10;
int a[] = {1, 2, 5, 4, 3, 2};
int b[N];
int mx, mi = INF;

int main() {
    // C++求整数数组长度的办法
    int len = sizeof(a) / sizeof(a[0]);

    //最大值,最小值
    for (int i = 0; i < len; i++)
        mx = max(mx, a[i]), mi = min(mi, a[i]); //最大值5最小值1

    //放入桶
    for (int i = 0; i < len; i++) b[a[i]]++;

    //排序结果
    for (int i = mi; i <= mx; i++) {
        for (int j = 1; j <= b[i]; j++)
            printf("%d ", i);
    }

    return 0;
}