I have an array of n integers that can only assume log n possible values (and any value). For example, in S = [349,12,12,283,349,283,283,12]
, there are only 3 different numbers (log 8 = 3)
.
I have to sort this array in less than O(nlogn)
time. Which algorithm should I use? Maybe Radix Sort with Counting Sort? What about its analysis?
Since it is a given that there will be only log(n)
unique elements, you could get the sorted list in O(n)
time using the algorithm below:
O(n)
steps.log(n)
based on their key.
k*log(k)
, where k
is size of the input. k
with log(n)
, we get complexity of this step as O(log(n)*log(log(n)))
.O(log(n)*log(log(n)))
< O(n)
, so overall complexity till this step is O(n) + O(log(n)*log(log(n)))
, which is equivalent to O(n)
again.O(n)
iterations here.So overall, the algorithm above will run in O(n) time.