views:

428

answers:

6

Notes: I've thought about Radix sort, bucket sort, counting sort.

Is there anyway to achieve big O(n)?

+7  A: 

A counting sort would be the obvious choice under these circumstances. Yes, properly implemented it should have linear complexity.

Jerry Coffin
+2  A: 

With counting sort you get O(N) if the range is fixed and small (like 1..100 :))

Razvi
+30  A: 

You can use counting sort.

Counting sort (sometimes referred to as ultra sort or math sort) is a sorting algorithm which (like bucket sort) takes advantage of knowing the range of the numbers in the array to be sorted (array A).

Counting sort is a stable sort and has a running time of Θ(n+k), where n and k are the lengths of the arrays A (the input array) and C (the counting array), respectively. In order for this algorithm to be efficient, k must not be much larger than n.

In this case k is 100 and n is 1000000.

Mark Byers
+1 Blindingly obvious, but had never seen it before. Thanks.
Neil Moss
+4  A: 

how about just counting the occurrence of each integer and then printing them all. sounds like O(n)

second
Yes, and that's exactly counting sort. This shows that most algorithms aren't hard; you can come up with them yourself. :-)
ShreevatsaR
+3  A: 

I assume, you mean you want to achieve a small O(n); then bucket sort would be fastest. In fact, since you know the range of the integers, then using bucket sort simply becomes a problem of counting the occurrences of the numbers which can be done in O(n), i.e. linear time.

The so-called counting sort is simply a special case of bucket sort.

Lie Ryan
A: 
Jörg W Mittag