什么是计数排序?

计数排序(Count Sort)是一个非基于比较的排序算法,该算法于1954年由 Harold H. Seward 提出。它的优势在于在对一定范围内的整数排序时,它的复杂度为Ο(n+k)(其中k是整数的范围),快于任何比较排序算法。

计数排序的思想是在给定的一组序列中,先找出该序列中的最大值和最小值,从而确定需要开辟多大的辅助空间,每一个数在对应的辅助空间中都有唯一的下标。

  1. 找出序列中最大值和最小值,开辟Max-Min+1的辅助空间
  2. 最小的数对应下标为0的位置,遇到一个数就给对应下标处的值+1,。
  3. 遍历一遍辅助空间,就可以得到有序的一组序列

这里写图片描述

#include <iostream>
using namespace std;

void countSort(int data[], int len)
{
    //find the min, max value of the array data
    int min = data[0];
    int max = min;
    for(int i = 1; i < len; i++)
    {
        if(data[i] < min )
            min = data[i];

        if(data[i] > max)
            max = data[i];
    }

    //Initialize the temp array
    int* temp = new int[max-min+1];
    for(int i = 0; i < max-min+1; i++)
        temp[i] = 0;

    //Count the time that appears in the array, then mark it in the temp array
    for(int i = 0; i < len; i++)
        temp[data[i] - min]++;

    //Go through the temp array, assign the value back to target array accroding to each data appear time.
    int j = 0;
    for(int i = 0; i < max-min+1; i++)
    {
        while((temp[i]--) > 0)
            data[j++] = min + i;
    }

    delete[] temp;

}

int main() {

    int arr[10] = {1,5,4,3,7,6,9,10,8,2};
    countSort(arr, 10);

    for(int i = 0; i < 10; i++)
        cout << arr[i] << endl;

    return 0;
}

 

  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值