Just a simple algorithm to sort small integers, but it must be O(n).
5 Answers
A radix sort is one approach that's O(n). Since you're dealing with small integers, it shouldn't be too hard to implement.
6 Comments
O(n). But radix sort is still the closest thing I can think of.n is smaller, chances are the k can also be decreased. So by fixing k at a large value, you are "slowing down" the smaller values of n by forcing them to use a larger than necessary k. This is a totally valid argument and as his answer mentions, is part of the "fine print" of the O(n) of the radix sort.Of course the fine print in the definition of O(n) there gets you. The radix sort, eg, is really n*log(n) when you figure that you must create a deeper tree as you accommodate more values -- they just manage to define it as O(n) by the trick of capping the number of values to be sorted. There's no way to really beat n*log(n) in the general sense.
Eg, for 8-bit values I can easily achieve O(n) by simply having a 256-entry array. But if I go to, say, even 32-bit values then I must have an array with 4G entries, and the address decoder for the memory chip for that array will have grown with log(n) of the size of the memory chip. Yes, I can say that the version with 4G entries is O(n), but at a electronic level the addressing is log(n) slower and more complex. Additionally, the buses inside the chip must drive more current and it will take longer for a memory cell, once "read", to dump its contents onto the bus. And all those effects are log(n).
Comments
Simply put :
- If you have no prior information on your number you're sorting, you cannot do better than O(nlogn) in average
- If you have more information (like the fact that you're dealing with integers), you can have some O(n) algorithms
A great resource are these Wikipedia tables. Have a look at the second one.
Comments
To the best of my knowledge, comparison based sorting algorithms share a lower bound of O(nlogn). To achieve O(n), we probably can't use any comparison based algorithms. Also, the input must bear additional properties. In your example, small integers, I guess, means that the integers fall within a specified range. If that were the case, you could try bucket/radix sort algorithm, which does not require any comparisons. For a simple example, suppose you have n integers to be sorted, all of which belong to the interval [1, 1000]. You just make 1000 buckets, and go over the n integers, if the integer is equal to 500, it goes to bucket 500, etc. Finally you concatenate all the buckets to obtain the sorted list. This algorithm takes O(n).
Comments
The optimum for comparison based sort is O(n*log(n)), the proof is not very difficult. BUT you may use counting sort, which is enumeration based or very similar bucket sort... You may also use radix sort, but it is not sort itself. Radix sort only iteratively calls some other stable sort...