计数排序 counting sort

定义:

  Counting sort is a stable sorting technique, which is used to sort objects according to the keys that are small numbers. It counts the number of keys whose key values are same. This sorting technique is effective when the difference between different keys are not so big, otherwise, it can increase the space complexity.

  计数排序是一种稳定的排序算法,用于根据较小的键对对象进行排序。 它计算键值相同的键的数量。 当不同键之间的差异不太大时,此排序技术非常有效,否则会增加空间复杂度。

  计数排序是一种通过对每个数组中的每个元素进行相应的计数统计,通过计数值确定元素的正确位置的排序算法。计数排序需要知道待排序数据的取值范围,以方便申请辅助空间,这是计数排序的一个缺点。

动画演示,见:https://www.jianshu.com/p/0807c3557dc2

例题:

给定一个包含红色、白色和蓝色,一共 n 个元素的数组,原地对它们进行排序,使得相同颜色的元素相邻,并按照红色、白色、蓝色顺序排列。

此题中,我们使用整数 0、 1 和 2 分别表示红色、白色和蓝色。

进阶:

  • 你可以不使用代码库中的排序函数来解决这道题吗?
  • 你能想出一个仅使用常数空间的一趟扫描算法吗?

示例 1:

输入:nums = [2,0,2,1,1,0]
输出:[0,0,1,1,2,2]

示例 2:

输入:nums = [2,0,1]
输出:[0,1,2]

示例 3:

输入:nums = [0]
输出:[0]

示例 4:

输入:nums = [1]
输出:[1]

提示:

  • n == nums.length
  • 1 <= n <= 300
  • nums[i] 为 01 或 2

代码:

void sortColors(vector<int>& nums) 
{
    if (nums.size() < 2)
        return;
    map<int, int> keyMap;    //插入值后,map根据key的值从小到大排序
    for (auto val : nums)
    {
        keyMap[val]++;
    }

    int idx = 0;
    for (map<int, int>::iterator it = keyMap.begin(); it != keyMap.end(); it++)
    {
        for (int i = idx; i < idx + it->second; i++)
        {
            nums[i] = it->first;
        }
        idx += it->second;
    }
}
原文地址:https://www.cnblogs.com/zyk1113/p/14066169.html