Exemple #1
0
        private static void IntrospectiveSort(T[] keys, int left, int length)
        {
            if (length < 2)
            {
                return;
            }

            IntroSort(keys, left, length + left - 1, 2 * ArraySorterHelper.FloorLog2(keys.Length));
        }
        private static int PickPivotAndPartition <T, TComparer>(T[] keys, int lo, int hi, TComparer comparer)
            where T : struct
            where TComparer : ICopyFreeComparer <T>
        {
            // Compute median-of-three.  But also partition them, since we've done the comparison.
            int median = lo + ((hi - lo) / 2);

            //// Sort lo, mid and hi appropriately, then pick mid as the pivot.

            if (lo != median)
            {
                SwapIfGreaterWithItems(keys, lo, median, comparer);
            }

            if (lo != hi)
            {
                SwapIfGreaterWithItems(keys, lo, hi, comparer);
            }

            if (median != hi)
            {
                SwapIfGreaterWithItems(keys, median, hi, comparer);
            }

            T pivot = keys[median];

            ArraySorterHelper.Swap(keys, median, hi - 1);

            int left = lo, right = hi - 1;

            // We already partitioned lo and hi and put the pivot in hi - 1.  And we pre-increment & decrement below.
            while (left < right)
            {
                while (left < (hi - 1) && comparer.Compare(ref keys[++left], ref pivot) < 0)
                {
                }

                while (right > lo && comparer.Compare(ref pivot, ref keys[--right]) < 0)
                {
                }

                if (left >= right)
                {
                    break;
                }

                ArraySorterHelper.Swap(keys, left, right);
            }

            // Put pivot in the right location.
            ArraySorterHelper.Swap(keys, left, hi - 1);
            return(left);
        }
        internal static void IntrospectiveSort <T, TComparer>(T[] keys, int indexFrom, int indexTo, TComparer comparer)
            where T : struct
            where TComparer : ICopyFreeComparer <T>
        {
            int length = indexTo - indexFrom + 1;

            if (length < 2)
            {
                return;
            }

            IntroSort(keys, indexFrom, indexTo, 2 * ArraySorterHelper.FloorLog2(length), comparer);
        }
        private static void Heapsort <T, TComparer>(T[] keys, int lo, int hi, TComparer comparer)
            where T : struct
            where TComparer : ICopyFreeComparer <T>
        {
            int n = hi - lo + 1;

            for (int i = n / 2; i >= 1; i = i - 1)
            {
                DownHeap(keys, i, n, lo, comparer);
            }

            for (int i = n; i > 1; i = i - 1)
            {
                ArraySorterHelper.Swap(keys, lo, lo + i - 1);
                DownHeap(keys, 1, i - 1, lo, comparer);
            }
        }