简体   繁体   English

就时间复杂度而言,计数或基数排序哪个更受欢迎?

[英]Counting or Radix sort which is preferred in terms of time complexity?

I'm given with an array of integers from the set {0,1,…,n} wherein I need to sort the array in time O(n).我从集合 {0,1,…,n} 中得到一个整数数组,其中我需要在 O(n) 时间内对数组进行排序。 But I'm not sure whether to do Radix /Counting sort for this problem.但我不确定是否对这个问题进行基数/计数排序。 Can anyone give your suggestions on this?任何人都可以就此提出您的建议吗?

If you need to sort in O(n) time, then counting sort is the only option.如果你需要在O(n)时间内排序,那么计数排序是唯一的选择。 It has Θ(n) time and Θ(n) space complexity.它有Θ(n)时间和Θ(n)空间复杂度。

Radix sort requires O(n log(n)) time in the worst case (since length of the key in your case is log(n) ), and quicksort is O(n log(n)) in average case and can be O(n²) in the worst case, depending on the implementation.在最坏的情况下,基数排序需要O(n log(n))时间(因为在您的情况下键的长度是log(n) ),而快速排序在平均情况下是O(n log(n))并且可以是O(n²)在最坏的情况下,取决于实现。

If n is small enough that an array of n elements will fit in memory, then a counting sort would be fastest.如果 n 小到足以让 n 个元素的数组适合内存,那么计数排序将是最快的。

For larger n, a radix sort is needed.对于较大的 n,需要进行基数排序。 If the keys are stored in 32 bit or 64 bit integers, then a base 256 radix sort will take 4 passes for 32 bits, 8 passes for 64 bits.如果键以 32 位或 64 位整数形式存储,则基数 256 基数排序将需要 4 遍(32 位),8 遍(64 位)。 Since time complexity ignores constants, then such a radix sort technically has time complexity O(n).由于时间复杂度忽略了常数,那么这种基数排序在技术上的时间复杂度为 O(n)。 However, if the radix sort uses the maximum key value to reduce the number of passes, then time complexity would be O(n log(n)) (actual complexity would be n ceil(log256(n))).但是,如果基数排序使用最大键值来减少传递次数,那么时间复杂度将为 O(n log(n))(实际复杂度为 n ceil(log256(n)))。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM