This commit is contained in:
Ingy döt Net 2013-10-27 22:24:23 +00:00
parent 6f050a029e
commit 776bba907c
3887 changed files with 59894 additions and 7280 deletions

View file

@ -1,49 +1,47 @@
import std.stdio, std.algorithm, std.array, std.traits;
template AreSortableArrayItems(T) {
enum AreSortableArrayItems = isMutable!T &&
__traits(compiles, T.init < T.init) &&
!isNarrowString!(T[]);
}
enum AreSortableArrayItems(T) = isMutable!T &&
__traits(compiles, T.init < T.init) &&
!isNarrowString!(T[]);
void selectionSort(T)(T[] data) if (AreSortableArrayItems!T) {
foreach (i, ref d; data)
d.swap(data[i .. $].minPos().front);
foreach (immutable i, ref d; data)
data.drop(i).minPos[0].swap(d);
} unittest {
int[] a0;
selectionSort(a0);
a0.selectionSort;
auto a1 = [1];
selectionSort(a1);
a1.selectionSort;
assert(a1 == [1]);
auto a2 = ["a", "b"];
selectionSort(a2);
a2.selectionSort;
assert(a2 == ["a", "b"]);
auto a3 = ["b", "a"];
selectionSort(a3);
a3.selectionSort;
assert(a3 == ["a", "b"]);
auto a4 = ['a', 'b'];
static assert(!__traits(compiles, selectionSort(a4)));
static assert(!__traits(compiles, a4.selectionSort));
dchar[] a5 = ['b', 'a'];
selectionSort(a5);
a5.selectionSort;
assert(a5 == "ab"d);
import std.typecons;
alias Nullable!int N;
auto a6 = [N(2), N(1)];
selectionSort(a6); // Not nothrow.
a6.selectionSort; // Not nothrow.
assert(a6 == [N(1), N(2)]);
auto a7 = [1.0+0i, 2.0+0i]; // To be deprecated.
static assert(!__traits(compiles, selectionSort(a7)));
static assert(!__traits(compiles, a7.selectionSort));
import std.complex;
auto a8 = [complex(1), complex(2)];
static assert(!__traits(compiles, selectionSort(a8)));
static assert(!__traits(compiles, a8.selectionSort));
static struct F {
int x;
@ -52,12 +50,12 @@ void selectionSort(T)(T[] data) if (AreSortableArrayItems!T) {
}
}
auto a9 = [F(2), F(1)];
selectionSort(a9);
a9.selectionSort;
assert(a9 == [F(1), F(2)]);
}
void main() {
auto a = [3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5, 8, 9, 7, 9, 3, 2];
a.selectionSort();
writeln(a);
a.selectionSort;
a.writeln;
}

View file

@ -0,0 +1,17 @@
selection_sort([], []).
selection_sort([H | L], [H1 | L2]) :-
exchange(H, L, H1, L1),
selection_sort(L1, L2).
exchange(H, [], H, []).
exchange(H, L, H1, L1) :-
min_list(L, H2),
( H < H2
-> H1 = H, L1 = L
; H1 = H2,
% does the exchange of the number H
% and the min of the list
nth0(Ind, L, H1, L2),
nth0(Ind, L1, H, L2)).