sorting network
排序网络的定义可参考维基百科。其中,如何构造排序网络是一个很有意思的话题,一个基本的思想是递归的构造sorter来完成对2^k个输入的排序网络。
这是我们算法设计这门课的一个作业,用代码实现对任意形如n=2^k个输入的排序网络构造。
递归说明
建立一个n=2^k个输入的排序网络,有两个步骤:
- 构造2个子sorter,每个的大小均为n/2;
- 构造一个merger,大小为n。
每一个子sorter里面都可能包含merger(实现对2个n/4大小的sorter的合并),结束条件是当输入为2时,sorter就只有一个连线,不包含子merger。
代码实现:
/**
Program Function: Implement a sorting network constructor for any N=2^k inputs
Author: Meditator_hkx
Input: N
Output: the link rules
*/
#include <stdio.h>
#define N 64
void construct_lines(int *p_set, int n);
void add_sorter(int *p_set, int n);
void add_merger(int *p_set, int n);
int main() {
int *p_set = new int[N];
// Obtain line numbers of n inputs
construct_lines(p_set, N);
// Construct sorters recursively
// construct_sorting_network(p_set, N);
add_sorter(p_set, N);
return 0;
}
void construct_lines(int set[], int n) {
int i = 1;
for (;i <= n;i++) {
set[i-1] = i;
}
i = 1;
printf("The line set is: \n");
for (;i <= n;i++) {
printf(" %d", set[i-1]);
}
printf("\n");
}
void addLink(int a, int b) {
printf("Link line %d and line %d\n", a, b);
}
void add_sorter(int *p_set, int n) {
if (n == 2) {
addLink(p_set[0], p_set[1]);
return;
}
else {
printf("------Start to construct front half of Sorter (size %d)-----\n", n/2);
add_sorter(p_set, n/2);
printf("------End to construct front half of Sorter (size %d)-----\n", n/2);
printf("------Start to construct back half of Sorter (size %d)-----\n", n/2);
add_sorter(p_set+n/2, n/2);
printf("------End to construct back half of Sorter (size %d)-----\n", n/2);
printf("------Start to construct merger of size %d------\n", n);
add_merger(p_set, n);
printf("------End to construct merger of size %d------\n", n);
return;
}
}
void add_merger(int *p_set, int n) {
// Step 1: head-tail link
int i = 0;
int j = n-1;
while (i < j) {
addLink(p_set[i], p_set[j]);
i++;j--;
}
// Step 2: add step links
int step = n / 4;
while (step > 1) {
for (i = 0; i + step < n; i++) {
addLink(p_set[i], p_set[i+step]);
}
step = step / 2;
}
// Step 3: add last column links
for (i = 0; i < n; i=i+2) {
addLink(p_set[i], p_set[i+1]);
}
return;
}
输出结果实例
N = 2:
The line set is:
1 2
Link line 1 and line 2
N = 4:
The line set is:
1 2 3 4
------Start to construct front half of Sorter (size 2)-----
Link line 1 and line 2
------End to construct front half of Sorter (size 2)-----
------