[英]sort array of size n
if an array of size n has only 3 values 0 ,1 and 2 (repeated any number of times) what is the best way to sort them. 如果大小为n的数组只有3个值0,1和2(重复任意次数),那么对它们进行排序的最佳方法是什么。 best indicates complexity.
最能说明复杂性。 consider space and time complexity both
同时考虑时空复杂度
计算每个数字的出现次数,然后用正确的计数填充数组,这是O(n)
Sound's a lot like Dijkstra's Dutch National Flag Problem. 声音很像Dijkstra的荷兰国旗问题。
If you need a solution that doesn't use counting, check out http://www.csse.monash.edu.au/~lloyd/tildeAlgDS/Sort/Flag/ 如果您需要不使用计数的解决方案,请访问http://www.csse.monash.edu.au/~lloyd/tildeAlgDS/Sort/Flag/
Untested C-style solution: 未经测试的C风格解决方案:
int count[3] = {0, 0, 0};
for (int i = 0; i < n; ++i)
++count[array[i]];
int pos = 0;
for (int c = 0; c < 3; ++c)
for (int i = array[c]; i; --i)
array[pos++] = c;
Haskell two-liner: Haskell两线:
count xs = Map.toList $ Map.fromListWith (+) [ (x, 1) | x <- xs ]
countingSort xs = concatMap ( \(x, n) -> replicate n x) (count xs)
> countingSort [2,0,2,1,2,2,1,0,2,1]
[0,0,1,1,1,2,2,2,2,2]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.