c - 排序网络如何击败通用排序算法?

标签 c algorithm sorting comparison sorting-network

引用fastest sort of fixed length 6 int array ,我不完全明白这是怎么回事sorting network击败像 insertion sort 这样的算法.

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

Linux 32 bits, gcc 4.4.1, Intel Core 2 Quad Q8300, -O2

  • Insertion Sort (Daniel Stutzbach) : 1425
  • Sorting Networks (Daniel Stutzbach) : 1080

使用的代码如下:

Insertion Sort (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;
    }
}

Sorting Networks (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
}

我知道排序网络非常适合并行排序,因为有些步骤是独立于其他步骤的。但是这里我们没有使用并行化。

我希望它会更快,因为它具有预先知道元素的确切数量的优势。 插入排序到底在哪里以及为什么会进行不必要的比较?

编辑 1:

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

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}\
};\

最佳答案

But here we are not using the parallelization.

现代 CPU 可以判断指令何时独立并并行执行它们。因此,即使只有一个线程,也可以利用排序网络的并行性。

Where exactly does insertion sort make unnecessary comparisons?

查看额外比较的最简单方法是手动做一个例子。

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

关于c - 排序网络如何击败通用排序算法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3901079/

相关文章:

javascript - 如何在 mongodb 中维护排序的属性顺序?

arrays - 证明或反驳 : There is a general sorting algorithm which can sort an array of length n in O(n) if it's min-heap-ordered

"key"函数不足的Python排序

c - mainCRTStartup 的签名是什么

c++ - Emacs C/C++ 注释填充 : want paragraphs in comment to not be merged

java - 我应该在这里使用哪种算法?在字符串数组中查找字符串

python - 如何在 Python 3 中将幻方转换为合适的幻方?

algorithm - 针对对称邻接矩阵优化 Floyd-Warshall

c - 缓冲区溢出,不是预期的结果

c++ - 宏定义中双重否定的目的是什么,比如 (!!(expr))?