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

后端 未结 12 3159
青春惊慌失措
青春惊慌失措 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:11

    Here is an implementation of an odd-even merge sort network in C99 (sorry for the "wrong" language):

    #define CMP_SWAP(i, j) if (a[i] > a[j])              \
        { int tmp = a[i]; a[i] = a[j]; a[j] = tmp; }
    
    void sort8_network(int *a)
    {
        CMP_SWAP(0, 1); CMP_SWAP(2, 3); CMP_SWAP(4, 5); CMP_SWAP(6, 7);
        CMP_SWAP(0, 2); CMP_SWAP(1, 3); CMP_SWAP(4, 6); CMP_SWAP(5, 7);
        CMP_SWAP(1, 2); CMP_SWAP(5, 6); CMP_SWAP(0, 4); CMP_SWAP(1, 5);
        CMP_SWAP(2, 6); CMP_SWAP(3, 7); CMP_SWAP(2, 4); CMP_SWAP(3, 5);
        CMP_SWAP(1, 2); CMP_SWAP(3, 4); CMP_SWAP(5, 6);
    }
    

    I timed it on my machine against insertion sort

    void sort8_insertion(int *a)
    {
        for (int i = 1; i < 8; i++)
        {
            int tmp = a[i];
            int j = i;
            for (; j && tmp < a[j - 1]; --j)
                a[j] = a[j - 1];
            a[j] = tmp;
        }
    }
    

    For about 10 million sorts (exactly 250 times all the 40320 possible permutations), the sort network took 0.39 seconds while insertion sort took 0.88 seconds. Seems to me both are fast enough. (The figures inlcude about 0.04 seconds for generating the permutations.)

提交回复
热议问题