代码之家  ›  专栏  ›  技术社区  ›  Aakash Goel

排序网络如何击败一般排序算法?

  •  14
  • Aakash Goel  · 技术社区  · 15 年前

    参考 fastest sort of fixed length 6 int array ,我不完全理解 sorting network 胜过算法 insertion sort .

    从这个问题来看,这里是完成排序所需的CPU周期数的比较:

    Linux 32位,GCC 4.4.1,Intel Core 2 Quad Q8300,-o2

    • 插入排序(Daniel Stutzbach):1425
    • 分类网络(Daniel Stutzbach):1080

    使用的代码如下:

    插入排序(Daniel Stutzbach)

    static inline void sort6_insertion_sort_v2(int *d){
        int i, j;
        for (i = 1; i < 6; i++) {
                int tmp = d[i];
                for (j = i; j >= 1 && tmp < d[j-1]; j--)
                        d[j] = d[j-1];
                d[j] = tmp;
        }
    }
    

    分类网络(Daniel Stutzbach)

    static inline void sort6_sorting_network_v1(int * d){
    #define SWAP(x,y) if (d[y] < d[x]) { int tmp = d[x]; d[x] = d[y]; d[y] = tmp; }
        SWAP(1, 2);
        SWAP(0, 2);
        SWAP(0, 1);
        SWAP(4, 5);
        SWAP(3, 5);
        SWAP(3, 4);
        SWAP(0, 3);
        SWAP(1, 4);
        SWAP(2, 5);
        SWAP(2, 4);
        SWAP(1, 3);
        SWAP(2, 3);
    #undef SWAP
    }
    

    我知道,排序网络确实很适合并行排序,因为有些步骤独立于其他步骤。但这里我们不使用平行化。

    我希望它更快,因为它的优点是事先知道元素的确切数量。 插入排序在何处进行不必要的比较?为什么要进行不必要的比较?

    Eddi1:

    这是将这些代码与以下代码进行比较的输入集:

    int d[6][6] = {\
        {1, 2, 3, 4, 5, 6},\
        {6, 5, 4, 3, 2, 1},\
        {100, 2, 300, 4, 500, 6},\
        {100, 2, 3, 4, 500, 6},\
        {1, 200, 3, 4, 5, 600},\
        {1, 1, 2, 1, 2, 1}\
    };\
    
    6 回复  |  直到 10 年前
        1
  •  19
  •   Daniel Stutzbach Edward Leno    15 年前

    Insertion sort:
    6 5 4 3 2 1
    5 6 4 3 2 1
    5 4 6 3 2 1
    4 5 6 3 2 1
    4 5 3 6 2 1
    4 3 5 6 2 1
    3 4 5 6 2 1
    3 4 5 2 6 1
    3 4 2 5 6 1
    3 2 4 5 6 1
    2 3 4 5 6 1
    2 3 4 5 1 6
    2 3 4 1 5 6
    2 3 1 4 5 6
    2 1 3 4 5 6
    1 2 3 4 5 6
    
    Sorting network:
    6 5 4 3 2 1
    6 4 5 3 2 1
    5 4 6 3 2 1
    4 5 6 3 2 1 # These three can execute in parallel with the first three
    4 5 6 3 1 2 #
    4 5 6 2 1 3 #
    4 5 6 1 2 3
    1 5 6 4 2 3
    1 2 6 4 5 3
    1 2 3 4 5 6
    1 2 3 4 5 6
    
        2
  •  4
  •   R.. GitHub STOP HELPING ICE    15 年前

    n

        3
  •  1
  •   Shay Erlichmen    15 年前
        4
  •  1
  •   ultimate cause    15 年前

        5
  •  0
  •   George    15 年前

        6
  •  0
  •   Community Mohan Dere    8 年前