11

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?

James Waldby - jwpat7
  • 8,593
  • 2
  • 22
  • 37

2 Answers2

10

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).

NPE
  • 486,780
  • 108
  • 951
  • 1,012
  • Thanks for the answer, i just wanted to make sure whether i understood right –  Mar 24 '13 at 14:25
3

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).

Robert S. Barnes
  • 39,711
  • 30
  • 131
  • 179
  • you are assuming `O(1)` operations on base `n` numbers. It seems unlikely to hold in general. – jfs Jan 06 '14 at 23:14