c语言实现计数排序算法,要求包含累计数组
时间: 2023-11-18 13:33:13 浏览: 39
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_NUM 1000 // 数组中最大值
#define MAX_SIZE 1000 // 数组的最大长度
void counting_sort(int arr[], int len);
int main()
{
int arr[MAX_SIZE];
int len;
printf("Enter the length of the array: ");
scanf("%d", &len);
printf("Enter the elements of the array: ");
for (int i = 0; i < len; i++) {
scanf("%d", &arr[i]);
}
counting_sort(arr, len);
printf("Sorted array: ");
for (int i = 0; i < len; i++) {
printf("%d ", arr[i]);
}
printf("\n");
return 0;
}
void counting_sort(int arr[], int len)
{
int count[MAX_NUM + 1];
int sorted_arr[len];
memset(count, 0, sizeof(count)); // 初始化为0
// 计数
for (int i = 0; i < len; i++) {
count[arr[i]]++;
}
// 累计
for (int i = 1; i <= MAX_NUM; i++) {
count[i] += count[i - 1];
}
// 排序
for (int i = len - 1; i >= 0; i--) {
sorted_arr[count[arr[i]] - 1] = arr[i];
count[arr[i]]--;
}
// 将排序后的数组复制回原数组
memcpy(arr, sorted_arr, sizeof(sorted_arr));
}
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![c](https://img-home.csdnimg.cn/images/20210720083646.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)