using System.Collections.Generic; using System.Linq; using System.Runtime.CompilerServices; namespace Dalamud.Utility; /// /// Extensions methods providing stable insertion sorts for IList. /// internal static class StableInsertionSortExtension { /// /// Perform a stable sort on a list. /// /// The list to sort. /// Selector to order by. /// Element type. /// Selected type. [MethodImpl(MethodImplOptions.AggressiveInlining | MethodImplOptions.AggressiveOptimization)] public static void StableSort(this IList list, Func selector) { var tmpList = new List(list.Count); tmpList.AddRange(list.OrderBy(selector)); for (var i = 0; i < tmpList.Count; ++i) list[i] = tmpList[i]; } /// /// Perform a stable sort on a list. /// /// The list to sort. /// Comparer to use when comparing items. /// Element type. [MethodImpl(MethodImplOptions.AggressiveInlining | MethodImplOptions.AggressiveOptimization)] public static void StableSort(this IList list, Comparison comparer) { var tmpList = new List<(T, int)>(list.Count); tmpList.AddRange(list.WithIndex()); tmpList.Sort((a, b) => { var ret = comparer(a.Item1, b.Item1); return ret != 0 ? ret : a.Item2.CompareTo(b.Item2); }); for (var i = 0; i < tmpList.Count; ++i) list[i] = tmpList[i].Item1; } }