编辑代码

#include <stdio.h>

// 计数排序 (基于比较))
void CountSort(int *arr, int len, int *temp) {
    int i, j;
    int count[len]; // 创建计数数组

    for (i = 0; i < len; i++) // 初始化计数数组
        count[i] = 0;

    for (i = 0; i < len - 1; i++) { // 外层循环,每次选取最前面一个元素
        for (j = i + 1; j < len; j++) { // 内层循环,每次让当前元素和它后面的元素比较
            if (arr[i] > arr[j]) { // 若前一个元素大于后一个元素,则让count[i]+1
                count[i]++;
            } else {
                count[j]++;
            }
        }
    }
    // 循环完毕,此时count数组里面的数据应该是对应arr数组中所在位置的最终下标

    for (i = 0; i < len; i++) {
        temp[count[i]] = arr[i]; // 创建临时数组,将count[i]作为arr的下标,存储在temp数组中,此时temp就是排好序的数组
    }
}

// 显示函数
void display(int *arr, int len) {
    for (int i = 0; i < len; i++)
        printf("%d ", arr[i]);
}

int main() {
    int arr[] = {15, 7, 6, 24, 3};
    int len = sizeof(arr) / sizeof(int);
    int temp[len];

    CountSort(arr, len, temp); // 调用计数排序函数对数组进行排序
    display(temp, len); // 显示排序后的数组
}