counting sort 计数排序 c语言实现

本文介绍了计数排序的基本原理,并提供了C语言的实现代码,详细解析了排序过程,适用于整数排序,效率高,适合大规模数据预处理。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >


/*
今天学习counting sort,下面是c的counting sort实现。。
这个版本比较简单,只能排 大于等于0的array,有负数的情况还要做一些改变。

需要注意的是,这个版本是一个 non-stable sorting 因为最后一个for loop,是从array的左边开始的,
对于这个例子stable或者non-stable都不重要,但如果要把counting sort作为radix sort的子程序的话,
就一定要保证最后一个loop是从array的右边开始,这样可以保证它一定是stable的。
*/

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

// finds max value of a given array.
int max(int *array, int SIZE) {
    int m = array[0];
    for (int i=1; i<SIZE; ++i) {
        if (array[i] > m) {
            m = array[i];
        }
    }
    return m;
}


int * countSort(int *array, int SIZE) {
    // finds upperbound
    int MAX = max(array, SIZE);
    
    // sets up the array for holding the count
    int count[MAX + 1];
    // this array is for output
    int *output = (int*) malloc(sizeof(int) * SIZE);
    // initilizes both arrays to all-0
    memset(count, 0, (MAX+1) * sizeof(int));
    memset(output, 0, SIZE * sizeof(int));
    
    // counts occurrence of element in to-be-sorted array
    for (int i=0; i<SIZE; i++) {
        count[array[i]] ++;
    }
    
    // sums up occurrence towards right
    // the value means the correct position an element should be.
    for (int i=1; i<(MAX+1); i++) {
        count[i] += count[i-1];
    }
    // sorts the array through mapping from count array.
    for (int j=0; j<SIZE; ++j) {
        output[count[array[j]] - 1] = array[j];
        count[array[j]] --;
    }
    
    return output;
}



int main()
{   
    // array to be sorted.
    int arr[] = {4, 9, 2, 4, 7, 6};
    int SIZE = sizeof(arr) / sizeof(int);
    int *result = countSort(arr, SIZE);
    // prints out sorted array.
    for (int i=0; i<SIZE; i++){
        printf("%d ", result[i]);
    }
    printf("\n");
    free(result);
    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值