What is the fastest sorting algorithm for a small number of integers?

后端 未结 12 2879
青春惊慌失措
青春惊慌失措 2021-02-20 18:45

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

相关标签:
12条回答
  • 2021-02-20 19:14

    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.

    0 讨论(0)
  • 2021-02-20 19:18

    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,
    • pigeonhole (bucket) sort with reuse of the buckets,
    • a bunch of if statements, and
    • insertion sort

    in 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.

    0 讨论(0)
  • 2021-02-20 19:18

    For integers, you could try radix-sort. It's O(N).

    0 讨论(0)
  • 2021-02-20 19:21

    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.

    0 讨论(0)
  • 2021-02-20 19:21

    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.

    0 讨论(0)
  • 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

    0 讨论(0)
提交回复
热议问题