首页 > 代码库 > Leetcode:Sort colors 计数排序

Leetcode:Sort colors 计数排序

Sort colors:

Given an array with n objects colored red, white or blue, sort them so that objects of the same color are adjacent, with the colors in the order red, 
white and blue.Here, we will use the integers
0, 1, and 2 to represent the color red, white, and blue respectively.

 

题解分析:

当我们已知待排序元素的值范围,可以有 T(n) = O(n)的排序方法

这个题目中,很显然,待排元素的值范围已知,其他的诸如 对学生成绩排序,对职工年龄排序 这些都可以应用计数排序

 计数排序的基本思想是对每一个输入元素x,确定出小于x的元素的个数。然后再将x直接放置在它在最终输出数组中的位置上。

class Solution {public:    void sortColors(int A[], int n) {        assert(A != NULL && n >= 0);        auto result = minmax_element(A, A + n);        int minVal = *result.first;        int maxVal = *result.second;        int totalCount = maxVal - minVal + 1;          if (totalCount == 1) return;        int* count = new int[totalCount]();                for (int i = 0; i < n; ++i) {            ++(count[A[i] - minVal]);        }                for (int i = 1; i < totalCount; ++i) {            count[i] += count[i-1];        }                int* tmp = new int[n]();        for (int i = n - 1; i >= 0; --i) {   // 必须从后往前,否则不是稳定的算法            tmp[count[A[i] - minVal] - 1] = A[i];            --(count[A[i] - minVal]);        }                copy(tmp, tmp + n, A);                delete[] count;        delete[] tmp;    }};

 

动画演示:http://www.cs.usfca.edu/~galles/visualization/CountingSort.html