Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sort n numbers between [0,n^2 - 1] in O(n)? [duplicate]

Possible Duplicate:
An array of length N can contain values 1,2,3 … N^2. Is it possible to sort in O(n) time?

Given n numbers at the range [0,n^2 -1] how can we sort them in O(n) run time ?

I have a feeling that the solution involves radix sort ,but I'm still missing something.

The n numbers are integers .

Any ideas ?

REMARK: not homework!

Regards

like image 210
JAN Avatar asked Aug 20 '12 17:08

JAN


People also ask

Is there an O 1 sorting algorithm?

Examples of sorting algorithms with O(1) space complexity include: selection sort, insertion sort, shell sort and heapsort.

How do you sort an array in 0 n?

If you can bound your input in some way with both a lower and upper bound (and maximum precision/value length), then you can use a Radix Sort which is O(n) . Similarly, Bucket Sort can have O(n) complexity in the best case, but degrades to O(n^2) for bad inputs.

Can sorting be done in O n time?

We have now introduced several algorithms that can sort n numbers in O(n lg n) time. Merge sort and heapsort achieve this upper bound in the worst case; quicksort achieves it on average.


2 Answers

The actual time will depend on the distribution of data that you have, but I would do the following:

  • Make n buckets.
  • Go through each number and put element with value i into bucket sqrt(i).
  • Go through each bucket, and perform radix sort on each element in the bucket.
like image 131
Kirby Avatar answered Oct 23 '22 05:10

Kirby


I think you're out of luck. Radix sort is O(k*n), where k is number of digits. In your case, k = log(n^2), resulting in O(n*log(n)).

like image 3
mbeckish Avatar answered Oct 23 '22 07:10

mbeckish