I am wondering what the fastest algorithm would be for this. I have 8 integers between 0 and 3000 and I need to sort them. Although there are only 8 integers, this operation w
The following citation from Bentley et al., Engineering a sort function could be interesting here:
Various improvements to insertion sort, including binary search, loop unrolling, and handling n=2 as a special case, were not helpful. The simplest code was the fastest.
(Emphasis mine.)
This suggests that plain insertion sort without fancy modifications would indeed be a good starting point. As Peter has noted, eight items is indeed a bit tricky because that lies squarely in the range which usually marks the cut-off between insertion sort and quicksort.
The fastest way is a sorting network implemented in hardware. Barring that, the fastest way is determined only by measuring. I'd try
std::sort
,if
statements, andin that order, because it's the easiest-to-hardest order (try to get insertion sort right the first time...) until you find something that's maintainable once the constant eight turns out to have the value nine.
Also, bubble sort, selection deserve and shell sort deserve notice. I've never actually implemented those because they have bad rep, but you could try them.
For integers, you could try radix-sort. It's O(N).
A good source for comparing sorting algos is http://www.sorting-algorithms.com/. Note that even the initial order status affect the results. But anyway for 8 integers even a plain bubble sort should do the job.
For positive integers, the fastest sort is known as abacus sort- it's O(n)
http://en.wikipedia.org/wiki/Abacus_sort
If you only have a very few items, then it's unlikely that you will notice any performance difference from choosing any particular algorithm.
I ran a library of sort algorithms against all permutations of {0, 429, 857, 1286, 1714, 2143, 2571, 3000}.
The fastest were:
name time stable in-place
AddressSort 0.537 No No
CenteredLinearInsertionSort 0.621 Yes No
CenteredBinaryInsertionSort 0.634 Yes No
BinaryInsertionSort 0.639 Yes Yes
...
QuickSort 0.650 No Yes
...
BubbleSort 0.802 Yes Yes
For more on AddressSort see http://portal.acm.org/citation.cfm?id=320834