private static void IntroSort(SegmentedArraySegment <T> keys, int depthLimit, Comparison <T> comparer) { LorettaDebug.Assert(keys.Length > 0); LorettaDebug.Assert(depthLimit >= 0); LorettaDebug.Assert(comparer != null); int partitionSize = keys.Length; while (partitionSize > 1) { if (partitionSize <= SegmentedArrayHelper.IntrosortSizeThreshold) { if (partitionSize == 2) { SwapIfGreater(keys, comparer, 0, 1); return; } if (partitionSize == 3) { SwapIfGreater(keys, comparer, 0, 1); SwapIfGreater(keys, comparer, 0, 2); SwapIfGreater(keys, comparer, 1, 2); return; } InsertionSort(keys[..partitionSize], comparer);
internal static void IntrospectiveSort(SegmentedArraySegment <T> keys, Comparison <T> comparer) { LorettaDebug.Assert(comparer != null); if (keys.Length > 1) { IntroSort(keys, 2 * (SegmentedArraySortUtils.Log2((uint)keys.Length) + 1), comparer); } }
private static void SwapIfGreater(SegmentedArraySegment <T> keys, Comparison <T> comparer, int i, int j) { LorettaDebug.Assert(i != j); if (comparer(keys[i], keys[j]) > 0) { (keys[j], keys[i]) = (keys[i], keys[j]); } }
internal static void Sort(SegmentedArraySegment <T> keys, Comparison <T> comparer) { LorettaDebug.Assert(comparer != null, "Check the arguments in the caller!"); // Add a try block here to detect bogus comparisons try { IntrospectiveSort(keys, comparer); } catch (IndexOutOfRangeException) { ThrowHelper.ThrowArgumentException_BadComparer(comparer); } catch (Exception e) { ThrowHelper.ThrowInvalidOperationException(ExceptionResource.InvalidOperation_IComparerFailed, e); } }
public static void Sort(SegmentedArraySegment <T> keys, IComparer <T>?comparer) { // Add a try block here to detect IComparers (or their // underlying IComparables, etc) that are bogus. try { comparer ??= Comparer <T> .Default; IntrospectiveSort(keys, comparer.Compare); } catch (IndexOutOfRangeException) { ThrowHelper.ThrowArgumentException_BadComparer(comparer); } catch (Exception e) { ThrowHelper.ThrowInvalidOperationException(ExceptionResource.InvalidOperation_IComparerFailed, e); } }
private static void Swap(SegmentedArraySegment <T> a, int i, int j) { LorettaDebug.Assert(i != j); (a[j], a[i]) = (a[i], a[j]); }