The time complexity of counting sort

会有一股神秘感。 提交于 2021-01-26 23:52:03

问题


I am taking an algorithms course and there I saw that the time complexity of counting sort is O(n+k) where k is the range of numbers and n is the input size. My question is, when the difference between k and n is too much, such as when k=O(n2)or O(n3), can we say that the complexity is O(n2) or O(n3)? Then in this case counting sort is not a wise approach and we can use merge sort. Am I right?


回答1:


Yes, you are exactly right on all counts.

Furthermore, we can make stronger statements: when k=O(n2) or O(n3), we can say that the complexity of the counting sort is Θ(n2) or Θ(n3).




回答2:


You can still sort in O(n) time, theoretically. If the range of values is say 1 to n3 then convert to base n and do a Radix sort. In base n the number has 3 digits, so your run time is O(3n + 3n) + O(n) for the base conversion. Overall O(n).



来源:https://stackoverflow.com/questions/15599610/the-time-complexity-of-counting-sort

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!