mirror of
https://github.com/krahets/hello-algo.git
synced 2024-12-25 00:56:29 +08:00
feat: add C counting_sort (#430)
* feat: add C counting_sort * Update CMakeLists.txt --------- Co-authored-by: Yudong Jin <krahets@163.com>
This commit is contained in:
parent
0659c54e77
commit
e539c44f63
2 changed files with 8 additions and 9 deletions
|
@ -1,5 +1,5 @@
|
|||
add_executable(bubble_sort bubble_sort.c)
|
||||
add_executable(counting_sort counting_sort.c)
|
||||
add_executable(insertion_sort insertion_sort.c)
|
||||
add_executable(quick_sort quick_sort.c)
|
||||
add_executable(radix_sort radix_sort.c)
|
||||
add_executable(counting_sort counting_sort.c)
|
||||
add_executable(radix_sort radix_sort.c)
|
||||
|
|
|
@ -1,8 +1,9 @@
|
|||
/**
|
||||
* File: counting_sort.c
|
||||
* Created Time: 2023-03-20
|
||||
* Author: Reanon (793584285@qq.com)
|
||||
* Author: Reanon (793584285@qq.com), Guanngxu (446678850@qq.com)
|
||||
*/
|
||||
|
||||
#include "../include/include.h"
|
||||
|
||||
/* 计数排序 */
|
||||
|
@ -30,7 +31,6 @@ void countingSortNaive(int nums[], int size) {
|
|||
}
|
||||
}
|
||||
|
||||
|
||||
/* 计数排序 */
|
||||
// 完整实现,可排序对象,并且是稳定排序
|
||||
void countingSort(int nums[], int size) {
|
||||
|
@ -57,10 +57,8 @@ void countingSort(int nums[], int size) {
|
|||
int *res = malloc(sizeof(int) * size);
|
||||
for (int i = size - 1; i >= 0; i--) {
|
||||
int num = nums[i];
|
||||
// 将 num 放置到对应索引处
|
||||
res[counter[num] - 1] = num;
|
||||
// 令前缀和自减 1 ,得到下次放置 num 的索引
|
||||
counter[num]--;
|
||||
res[counter[num] - 1] = num; // 将 num 放置到对应索引处
|
||||
counter[num]--; // 令前缀和自减 1 ,得到下次放置 num 的索引
|
||||
}
|
||||
// 使用结果数组 res 覆盖原数组 nums
|
||||
memcpy(nums, res, size * sizeof(int));
|
||||
|
@ -77,5 +75,6 @@ int main() {
|
|||
countingSort(nums, size);
|
||||
printf("计数排序完成后 nums = ");
|
||||
printArray(nums, size);
|
||||
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
|
|
Loading…
Reference in a new issue