考虑到参数的数量很少,并且它们的数量在编译时已知(无循环条件),这里的排序网络可能是最有效的。
冒泡排序很适合网络排序。我把这个扔在一起了。它很有效,而且非常简单:
import std.stdio, std.string;
void bubbleSort(T...)(ref T values)
{
static if (T.length > 1)
{
foreach(I, _; T[0 .. $ - 1])
{
pragma(msg, format("[%s %s]", I, I + 1));
compareAndSwap(values[I], values[I + 1]);
}
bubbleSort(values[0 .. $ - 1]);
}
}
void compareAndSwap(T)(ref T a, ref T b)
{
import std.algorithm;
if(a > b)
swap(a, b);
}
void main()
{
int a = 10;
int b = 30;
int c = 11;
int d = 20;
int e = 4;
int f = 330;
int g = 21;
int h = 110;
shellSort(a, b, c, d, e, f, g, h);
writefln("%s %s %s %s %s %s %s %s!", a, b, c, d, e, f, g, h);
}
虽然说实话,如果这是标准库,任何少于 10 个参数的排序网络都应该是手写的。
编辑:我完全改变了以前的算法,这实际上是非常低效的。冒泡排序不是最佳的,但它实际上对排序算法很有效。那里有一些编译指示可以查看已构建的网络。