问题
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