Exemple #1
0
        static void Main(string[] args)
        {
            TimSort Sort = new TimSort();
            Files   IO   = new Files();

            int[] Number_List = IO.ReadFile();
            Console.WriteLine("\nReading File From: {0}", IO.File_Path);
            Sort.TIMSORT(Number_List, Number_List.Length);

            Console.WriteLine("\nAfter Sorting Array:");
            Sort.Show(Number_List);

            IO.WriteFile(Number_List);
            Console.WriteLine("\n\nData Saved at: {0}", IO.Save_Path);

            Console.ReadKey();
        }
        /// <summary>
        /// This method constitute the entire API of this class
        /// </summary>
        /// <param name="a">the array to be sorted</param>
        /// <param name="lo"></param>
        /// <param name="hi"></param>
        /// <param name="c">Comparer</param>
        static void sort(T[] a, int lo, int hi, IComparer <T> c)
        {
            if (c == null)
            {
                //Arrays.sort(a, lo, hi);
                var work = a.ToList <T>();
                work.Sort();
                a = work.ToArray <T>();
                return;
            }

            rangeCheck(a.Length, lo, hi);
            int nRemaining = hi - lo;

            if (nRemaining < 2)
            {
                return;  // Arrays of size 0 and 1 are always sorted
            }
            // If array is small, do a "mini-TimSort" with no merges
            if (nRemaining < MIN_MERGE)
            {
                int initRunLen = countRunAndMakeAscending(a, lo, hi, c);
                binarySort(a, lo, hi, lo + initRunLen, c);
                return;
            }

            /**
             * March over the array once, left to right, finding natural runs,
             * extending short natural runs to minRun elements, and merging runs
             * to maintain stack invariant.
             */
            var ts     = new TimSort <T>(a, c);
            int minRun = minRunLength(nRemaining);

            do
            {
                // Identify next run
                int runLen = countRunAndMakeAscending(a, lo, hi, c);

                // If run is short, extend to min(minRun, nRemaining)
                if (runLen < minRun)
                {
                    int force = nRemaining <= minRun ? nRemaining : minRun;
                    binarySort(a, lo, lo + force, lo + runLen, c);
                    runLen = force;
                }

                // Push run onto pending-run stack, and maybe merge
                ts.pushRun(lo, runLen);
                ts.mergeCollapse();

                // Advance to find next run
                lo         += runLen;
                nRemaining -= runLen;
            } while (nRemaining != 0);

            // Merge all remaining runs to complete sort
            //assert lo == hi;
            ts.mergeForceCollapse();
            //assert ts.stackSize == 1;
        }