1 /** 2 Copyright: Copyright (c) 2016, Joakim Brännström. All rights reserved. 3 License: MPL-2 4 Author: Joakim Brännström (joakim.brannstrom@gmx.com) 5 6 This Source Code Form is subject to the terms of the Mozilla Public License, 7 v.2.0. If a copy of the MPL was not distributed with this file, You can obtain 8 one at http://mozilla.org/MPL/2.0/. 9 */ 10 module cpptooling.utility.sort; 11 12 import std.range.primitives : isInputRange; 13 14 /** Sort by using an index to remap the elements. 15 * 16 * TODO This is inefficient but gets the job done. 17 * 18 * Params: 19 * Pred = a func that takes arguments (Slice, indexA, indexB) and compares. 20 */ 21 auto indexSort(alias Pred, T)(T[] arr) @safe { 22 import std.algorithm : makeIndex, map; 23 24 auto index = new size_t[arr.length]; 25 makeIndex!((a, b) => Pred(a, b))(arr, index); 26 27 return index.map!(a => arr[a]); 28 } 29 30 @("shall be a sorted array") 31 unittest { 32 import std.array : array; 33 import test.extra_should : shouldEqualPretty; 34 35 string[] s = ["b", "c", "a", "d"]; 36 auto r = s.indexSort!((ref a, ref b) => a < b).array(); 37 38 r.shouldEqualPretty(["a", "b", "c", "d"]); 39 }