I'm stuck on this question: Given an array of n integers within the range of [0, 1, ... , n^5 - 1], how can you sort them in linear runtime? (O(n)) And more generally, if the range is [0, 1, ... , n^c - 1] (c is a natural constant bigger than 1) how would you do it? Describe a proper algorithm and explain. My first thought was to convert the numbers to base n in both of the cases and then use radix sort (which uses counting sort as the sorting algorithm), but I've been told that I can't count on it that the conversion from decimal base to base n is O(1) So basically I'm pretty stuck as I have no idea I can I do it... Would be glad for help.
CodePudding user response:
Hint: Bucket sort is a stable sort. So if you sort on condition A, then resort on condition B, you wind up sorted on B and then A.
Let's use //
for integer division (dropping the remainder) and %
for remainders. And now if you sort on x % m
and then sort the output on (x // m) % m
, you wind up with a list sorted on the last 2 digits in base b
.
Is that enough to get you going?
CodePudding user response:
The term "integers" implies the values are stored as binary numbers, not decimal. Since they're binary numbers use a base that is a power of 2, such as 256, which is common. Use shift
and and
instead of divide for fixed times.
For linear time complexity O(n), the code should sort based on the number of bits in an integer, typically 32 bits, so it would take 1 scan pass and 4 radix-sort passes. Since the 1 and 4 are constants, time complexity is O(n). If the sort is optimized to reduce the number of radix-sort passes based on range, although it is faster, it will have time complexity O(n log(range)).