コード例 #1
0
ファイル: QuickX.cs プロジェクト: zzhi/Algs4Net
        private static void Sort(IComparable[] a, int lo, int hi)
        {
            int N = hi - lo + 1;

            // cutoff to insertion sort
            if (N <= CUTOFF)
            {
                Insertion.Sort(a, lo, hi);
                return;
            }

            // use median-of-3 as partitioning element
            else if (N <= 40)
            {
                int m = median3(a, lo, lo + N / 2, hi);
                OrderHelper.Exch(a, m, lo);
            }

            // use Tukey ninther as partitioning element
            else
            {
                int eps     = N / 8;
                int mid     = lo + N / 2;
                int m1      = median3(a, lo, lo + eps, lo + eps + eps);
                int m2      = median3(a, mid - eps, mid, mid + eps);
                int m3      = median3(a, hi - eps - eps, hi - eps, hi);
                int ninther = median3(a, m1, m2, m3);
                OrderHelper.Exch(a, ninther, lo);
            }

            // Bentley-McIlroy 3-way partitioning
            int         i = lo, j = hi + 1;
            int         p = lo, q = hi + 1;
            IComparable v = a[lo];

            while (true)
            {
                while (OrderHelper.Less(a[++i], v))
                {
                    if (i == hi)
                    {
                        break;
                    }
                }
                while (OrderHelper.Less(v, a[--j]))
                {
                    if (j == lo)
                    {
                        break;
                    }
                }

                // pointers cross
                if (i == j && OrderHelper.Eq(a[i], v))
                {
                    OrderHelper.Exch(a, ++p, i);
                }
                if (i >= j)
                {
                    break;
                }

                OrderHelper.Exch(a, i, j);
                if (OrderHelper.Eq(a[i], v))
                {
                    OrderHelper.Exch(a, ++p, i);
                }
                if (OrderHelper.Eq(a[j], v))
                {
                    OrderHelper.Exch(a, --q, j);
                }
            }


            i = j + 1;
            for (int k = lo; k <= p; k++)
            {
                OrderHelper.Exch(a, k, j--);
            }
            for (int k = hi; k >= q; k--)
            {
                OrderHelper.Exch(a, k, i++);
            }

            Sort(a, lo, j);
            Sort(a, i, hi);
        }