Comment #0 by bearophile_hugs — 2014-09-16T14:38:16Z
A pair of overloaded functions like this could be useful to add to Phobos to avoid most of the template bloat caused by std.algorithm.sort in the situations where the maximum sorting performance and flexibility (this just accepts an array) is not strictly necessary:
import std.array: empty;
import core.stdc.stdlib: qsort;
import std.range: hasSwappableElements, hasAssignableElements;
import std.traits: isCallable, ReturnType, arity;
void podSort(T)(T[] items)
if (__traits(isPOD, T) &&
hasSwappableElements!(typeof(items)) &&
hasAssignableElements!(typeof(items))) {
if (items.empty)
return;
static extern(C) int cmp(const void* a, const void* b) {
auto x = cast(T*)a;
auto y = cast(T*)b;
return (*x == *y) ? 0 : ((*x < *y) ? -1 : 1);
}
qsort(items.ptr,
items.length,
T.sizeof,
&cmp);
}
void podSort(alias cmp, T)(T[] items)
if (__traits(isPOD, T) &&
hasSwappableElements!(typeof(items)) &&
hasAssignableElements!(typeof(items)) &&
isCallable!cmp &&
is(ReturnType!cmp == int) &&
arity!cmp == 2) {
if (items.empty)
return;
extern(C) int ccmp(const void* a, const void* b) {
auto x = cast(T*)a;
auto y = cast(T*)b;
return cmp(*x, *y);
}
qsort(items.ptr,
items.length,
T.sizeof,
&ccmp);
}
//--------------------------
void main() {
import std.stdio;
auto a = [10, 7, 2, 11, 9, 0, 3];
auto b = a.dup;
a.podSort;
a.writeln;
static int cmp1(const ref int x, const ref int y) {
return (x == y) ? 0 : ((x > y) ? -1 : 1);
}
podSort!cmp1(b);
b.writeln; // reversed
}
(This code is not perfect, not well tested, its constraints are not very good. It's just to give an idea of what I meant).
Comment #1 by hsteoh — 2014-09-28T01:11:28Z
We might want to consider putting this in druntime for sorting native arrays.
Comment #2 by greensunny12 — 2018-03-31T14:50:59Z
> A pair of overloaded functions like this could be useful to add to Phobos to avoid most of the template bloat caused by std.algorithm.sort in the situations where the maximum sorting performance and flexibility (this just accepts an array) is not strictly necessary:
(OP proposes a solution with if constraint "bloat")
I think if there are any issues with std.algorithm.sort / its templates, we should try to address these instead of promoting such "workarounds" in the standard library.
Closing as WONTFIX.
Please feel free to open issues regarding sort or problems with templates.