编辑代码

#include <stdio.h>
#include <stdlib.h>

void counting_sort(int arr[], int n) {
    int max_value = arr[0];
    
    // 找到最大值
    for (int i = 1; i < n; i++) {
        if (arr[i] > max_value) {
            max_value = arr[i];
        }
    }

    // 创建计数数组
    int* count_array = (int*)malloc((max_value + 1) * sizeof(int));

    // 初始化计数数组
    for (int i = 0; i <= max_value; i++) {
        count_array[i] = 0;
    }

    // 计数
    for (int i = 0; i < n; i++) {
        count_array[arr[i]]++;
    }

    // 累加计数数组
    for (int i = 1; i <= max_value; i++) {
        count_array[i] += count_array[i - 1];
    }

    // 排序
    int* result = (int*)malloc(n * sizeof(int));
    for (int i = n - 1; i >= 0; i--) {
        result[count_array[arr[i]] - 1] = arr[i];
        count_array[arr[i]]--;
    }

    // 将排序结果复制回原数组
    for (int i = 0; i < n; i++) {
        arr[i] = result[i];
    }

    // 释放动态分配的内存
    free(count_array);
    free(result);
}

// 示例
int main() {
    int arr[] = {4, 2, 2, 8, 3, 3, 1};
    int n = sizeof(arr) / sizeof(arr[0]);

    counting_sort(arr, n);

    printf("排序后的数组: ");
    for (int i = 0; i < n; i++) {
        printf("%d ", arr[i]);
    }

    return 0;
}