示例#1
0
        public static int QuickSort <T>(this T[] arr, PivotChoice choice = PivotChoice.ChooseRandom)
            where T : IComparable <T>
        {
            ChoosePivotIndex <T> pivotIntFunc = CalcMedium;

            switch (choice)
            {
            case PivotChoice.AlwaysFirst:
                pivotIntFunc = (T[] ar, int left, int right) => left;
                break;

            case PivotChoice.AlwaysLast:
                pivotIntFunc = (T[] ar, int left, int right) => right;
                break;

            case PivotChoice.CalcMedium:
                pivotIntFunc = CalcMedium;
                break;

            case PivotChoice.ChooseRandom:
                Random rnd = new Random();
                pivotIntFunc = (T[] ar, int left, int right) => rnd.Next(left, right + 1);
                break;
            }
            return(Sort <T>(arr, 0, arr.Length - 1, pivotIntFunc));
        }
示例#2
0
        private static int Sort <T>(T[] arr, int left, int right, ChoosePivotIndex <T> pivotIntFunc)
            where T : IComparable <T>
        {
            int result = left < right ? right - left : 0;

            if (left < right + 1)
            {
                int pivotInd = pivotIntFunc(arr, left, right);
                pivotInd = Pivot(arr, left, right, pivotInd);
                if (left < pivotInd - 1)
                {
                    result += Sort <T>(arr, left, pivotInd - 1, pivotIntFunc);
                }
                if (pivotInd + 1 < right)
                {
                    result += Sort <T>(arr, pivotInd + 1, right, pivotIntFunc);
                }
            }
            return(result);
        }