public static void Main(string[] args)
        {
            List <int> array = new List <int>();

            int maxValue = 1000;
            int count    = 20;

            RandFilling(array, count, maxValue);
            array.MergeSort();
            Console.WriteLine("DefaultCompare:");
            PrintArray(array);
            array.Clear();

            RandFilling(array, count, maxValue);
            array.MergeSort(ReverseCompare);
            Console.WriteLine("ReverseCompare:");
            PrintArray(array);
            array.Clear();

            RandFilling(array, count, maxValue);
            array.MergeSort(0, (count / 2) - 1, null);
            Console.WriteLine("Sort the first half of array:");
            PrintArray(array);
            array.Clear();
            Console.ReadKey();
        }
示例#2
0
        private static void MenuClicked2()
        {
            var test = new List <int> {
                5, 6, 8, 3, 4
            };

            Debug.Log("排序前:" + test.GetString());
            test.MergeSort();
            Debug.Log("升序排序后:" + test.GetString());
            test.MergeSort((a, b) => - a.CompareTo(b));
            Debug.Log("降序排序后:" + test.GetString());
        }
        public override void CallingSortOnAnEmptyListRemainsEmpty()
        {
            IList <int> empty = new List <int>();

            empty.MergeSort();
            Assert.Empty(empty);
        }
示例#4
0
        public static void Test()
        {
            List <int> list = new List <int>();
            Random     ran  = new Random((int)DateTime.Now.Ticks);

            for (int i = 0; i < 100000; i++)
            {
                list.Add(ran.Next(1000, 1000000));
            }
            Console.WriteLine("测试开始");
            Stopwatch watch = new Stopwatch();

            Console.WriteLine("---快速排序---");
            watch.Start();
            var result = list.OrderBy(s => s);

            watch.Stop();
            Console.WriteLine("用时:{0},前十个:{1}", watch.ElapsedMilliseconds, string.Join(",", result.Take(10)));
            watch.Reset();
            Console.WriteLine("---归并排序---");
            watch.Start();
            list.MergeSort();
            watch.Stop();
            Console.WriteLine("用时:{0},前十个:{1}", watch.ElapsedMilliseconds, string.Join(",", list.Take(10)));
        }
		public static void DoTest ()
		{
            List<int> numbersList = new List<int> { 23, 42, 4, 16, 8, 15, 3, 9, 55, 0, 34, 12, 2, 46, 25 };

            var sortedList = numbersList.MergeSort();
			Debug.Assert (sortedList[0] == 0, "Wrong min value!");
		}
示例#6
0
        public void MergeSort_ListGetsSorted()
        {
            // Test sorting by the integer key
            var actual_int = new List <int>(randList_int).ConvertAll(x => new MyClass {
                myInt = x
            });

            actual_int = actual_int.MergeSort(x => x.myInt);

            Assert.AreEqual(expected_int.Count, actual_int.Count);
            expected_int.Each((o, i) => Assert.AreEqual(o.myInt, actual_int[i].myInt));

            //// Tessorting by theth DateTime key
            var actual_dt = new List <DateTime>(randList_dt).ConvertAll(x => new MyClass {
                myDt = x
            });

            actual_dt = actual_dt.MergeSort(x => x.myDt);

            Assert.AreEqual(expected_dt.Count, actual_dt.Count);
            expected_dt.Each((o, i) => Assert.AreEqual(o.myDt, actual_dt[i].myDt));

            //// Tessorting by theth string key
            var actual_str = new List <string>(randList_str).ConvertAll(x => new MyClass {
                myStr = x
            });

            actual_str = actual_str.MergeSort(x => x.myStr);

            Assert.AreEqual(expected_str.Count, actual_str.Count);
            expected_str.Each((o, i) => Assert.AreEqual(o.myStr, actual_str[i].myStr));
        }
示例#7
0
 public static void NotifyComplete(NodeFactory factory, List <ILBodyFixupSignature> completeListOfSigs)
 {
     completeListOfSigs.MergeSort(new ObjectNodeComparer(CompilerComparer.Instance));
     foreach (var ilbodyFixupSig in completeListOfSigs)
     {
         ilbodyFixupSig.GetModuleToken(factory);
     }
 }
示例#8
0
        static void Main(string[] args)
        {
            List <int> numbers = new List <int>(Console.ReadLine().Split(' ').Select(int.Parse).ToList());

            numbers.MergeSort();

            Console.WriteLine();
        }
        public void Return_Min_Value_Via_Merge_Sort()
        {
            var numbersList = new List <int> {
                23, 42, 4, 16, 8, 15, 3, 9, 55, 0, 34, 12, 2, 46, 25
            };
            var sortedList = numbersList.MergeSort();

            Assert.AreEqual(sortedList[0], 0);
        }
示例#10
0
        public void MergeSortTest()
        {
            Stopwatch timer = Stopwatch.StartNew();

            timer.Start();
            TestSet.MergeSort();
            timer.Stop();
            Console.WriteLine("SORT TIME " + timer.ElapsedMilliseconds);
        }
        public static void DoTest()
        {
            List <int> numbersList = new List <int> {
                23, 42, 4, 16, 8, 15, 3, 9, 55, 0, 34, 12, 2, 46, 25
            };

            var sortedList = numbersList.MergeSort();

            Debug.Assert(sortedList[0] == 0, "Wrong min value!");
        }
示例#12
0
        public static void DoTest()
        {
            List <int> numbersList = new List <int> {
                23, 42, 4, 16, 8, 15, 3, 9, 55, 0, 34, 12, 2, 46, 25
            };
            var sortedList = numbersList.MergeSort();

            int[] expectedSortedList = { 0, 2, 3, 4, 8, 9, 12, 15, 16, 23, 25, 34, 42, 46, 55 };
            Assert.True(sortedList.SequenceEqual(expectedSortedList));
        }
示例#13
0
        public void Test_MergeSort()
        {
            var list = new List <int>()
            {
                4, 5, 1, 9, 2, 1, 7, 9, 64, 3
            };

            list.MergeSort();
            Assert.True(list.IsSorted());
        }
示例#14
0
        public override ObjectData GetData(NodeFactory factory, bool relocsOnly = false)
        {
            ObjectDataBuilder builder = new ObjectDataBuilder(factory, relocsOnly);

            builder.RequireInitialPointerAlignment();
            builder.AddSymbol(this);

            EmitHeaderPrefix(ref builder);

            // Don't bother sorting if we're not emitting the contents
            if (!relocsOnly)
            {
                _items.MergeSort((x, y) => Comparer <int> .Default.Compare((int)x.Id, (int)y.Id));
            }

            // ReadyToRunHeader.Flags
            builder.EmitInt((int)_flags);

            // ReadyToRunHeader.NumberOfSections
            ObjectDataBuilder.Reservation sectionCountReservation = builder.ReserveInt();

            int count = 0;

            foreach (var item in _items)
            {
                // Skip empty entries
                if (!relocsOnly && item.Node is ObjectNode on && on.ShouldSkipEmittingObjectNode(factory))
                {
                    continue;
                }

                // Unmarked nodes are not part of the graph
                if (!item.Node.Marked && !(item.Node is ObjectNode))
                {
                    Debug.Assert(item.Node is DelayLoadMethodCallThunkNodeRange);
                    continue;
                }

                builder.EmitInt((int)item.Id);

                builder.EmitReloc(item.StartSymbol, RelocType.IMAGE_REL_BASED_ADDR32NB);

                // The header entry for the runtime functions table should not include the 4 byte 0xffffffff sentinel
                // value in the covered range.
                int delta = item.Id == ReadyToRunSectionType.RuntimeFunctions ? RuntimeFunctionsTableNode.SentinelSizeAdjustment : 0;
                builder.EmitReloc(item.StartSymbol, RelocType.IMAGE_REL_SYMBOL_SIZE, delta);

                count++;
            }

            builder.EmitInt(sectionCountReservation, count);

            return(builder.ToObjectData());
        }
        public IIterator Filter(
            FilterRequest.FnameRequest fname,
            IdStorage idStorage)
        {
            if (fname.IsNull != null)
            {
                if (fname.IsNull.Value)
                {
                    if (fname.Eq == null && fname.Any.Count == 0)
                    {
                        return(_null.GetIterator());
                    }
                    else
                    {
                        return(ListHelper.EmptyInt);
                    }
                }
            }

            if (fname.Eq != null && fname.Any.Count > 0)
            {
                if (fname.Any.Contains(fname.Eq))
                {
                    int eqId = _storage.Get(fname.Eq);
                    return(_byName[eqId]?.GetIterator() ?? ListHelper.EmptyInt);
                }
                else
                {
                    return(ListHelper.EmptyInt);
                }
            }

            if (fname.Any.Count > 0)
            {
                List <IIterator> enumerators = new List <IIterator>(fname.Any.Count);
                for (int i = 0; i < fname.Any.Count; i++)
                {
                    int nameId = _storage.Get(fname.Any[i]);
                    if (_byName[nameId] != null)
                    {
                        enumerators.Add(_byName[nameId].GetIterator());
                    }
                }

                return(enumerators.MergeSort());
            }
            else if (fname.Eq != null)
            {
                int eqId = _storage.Get(fname.Eq);
                return(_byName[eqId]?.GetIterator() ?? ListHelper.EmptyInt);
            }

            return(_ids.GetIterator());
        }
示例#16
0
        /// <summary>
        /// </summary>
        /// <param name="args">
        /// The args.
        /// </param>
        private static void Main(string[] args)
        {
            // Create an unsorted array of string elements
            int[] unsorted = { 10, 2, 8, 6, 4, 7, 9, 3, 5, 7 };

            // int[] unsorted = { 10, 2 };
            List<int> list = new List<int>(unsorted);

            list.MergeSort();
            list.QuickSort(0, list.Count - 1);
        }
示例#17
0
        public static void MergeSort(List <int> myList, StreamWriter fisier = null, StreamWriter fisierValori = null)
        {
            Stopwatch sw = Stopwatch.StartNew();

            myList.MergeSort();

            sw.Stop();

            fisier.WriteLine("Merge Sort");
            fisierValori.WriteLine(sw.Elapsed);
        }
示例#18
0
        public void MergeSort_Should_Sort()
        {
            IList <int> numbers = new List <int> {
                2, 4, 1, 3
            };

            numbers = numbers.MergeSort();

            Assert.That(numbers, Is.EqualTo(new List <int> {
                1, 2, 3, 4
            }));
        }
示例#19
0
        public void MergeSort()
        {
            var actual = new List <int>();

            actual.AddRange(new [] { 5, 3, 1, 4, 2 });
            var expected = new List <int>();

            expected.AddRange(new [] { 1, 2, 3, 4, 5 });

            actual.MergeSort();

            Assert.Equal(expected, actual);
        }
        public void MergeSort_ListComparer_SortedList()
        {
            foreach (var lst in Data.TestLists.Lists)
            {
                var expectedList = new List <int>(lst);
                expectedList.Sort();

                var testList = new List <int>(lst);
                testList.MergeSort(new Data.IntComparer());

                Assert.Equal(expectedList, testList);
            }
        }
示例#21
0
        static void Main(string[] args)
        {
            List<int> listOfIntegers = new List<int>() { 4, 23, 2, 15, 11, 64, 7, 3, 1 };
            List<int?> listOfNullableIntegers = new List<int?>() { 4, null, 2, 15, null, 64, 7, 11, 66, 5, 8 };
            List<string> listOfStrings = new List<string> {"asd", "asdf", "mnogodulugstring" , "s", "ae", string.Empty, "asdec"};

            listOfIntegers.BubbleSort();
            foreach (var item in listOfIntegers)
            {
                Console.Write("{0} ", item);
            }

            Console.WriteLine();

            listOfNullableIntegers.SelectionSort(new OddEvenComparer());
            foreach (var item in listOfNullableIntegers)
            {
                Console.Write("{0} ", item);
            }

            Console.WriteLine();

            listOfStrings.SelectionSort(new StringLengthComparer());
            foreach (var item in listOfStrings)
            {
                Console.Write("{0} ", item);
            }

            Console.WriteLine();

            Console.WriteLine(listOfIntegers.BSearch(1)); // 0

            List<int> listOfIntegersQS = new List<int>() { 4, 5, 1, 3, 2 };
            List<int> listOfIntegersMS = new List<int>() { 1, 7, 13, 3, 9, 5, 11 };

            listOfIntegersQS.QuickSort();
            foreach (var item in listOfIntegersQS)
            {
                Console.Write("{0} ", item);
            }

            Console.WriteLine();

            listOfIntegersMS.MergeSort();
            foreach (var item in listOfIntegersMS)
            {
                Console.Write("{0} ", item);
            }

            Console.WriteLine();
        }
示例#22
0
        public IIterator Filter(FilterRequest.SnameRequest sname, IdStorage idStorage)
        {
            if (sname.IsNull != null)
            {
                if (sname.IsNull.Value)
                {
                    if (sname.Eq == null && sname.Starts == null)
                    {
                        return(_null.GetIterator());
                    }
                    else
                    {
                        return(ListHelper.EmptyInt);
                    }
                }
            }

            if (sname.Eq != null && sname.Starts != null)
            {
                if (sname.Eq.StartsWith(sname.Starts))
                {
                    return(_byName.GetValueOrDefault(_storage.Get(sname.Eq))?.GetIterator() ?? ListHelper.EmptyInt);
                }
                else
                {
                    return(ListHelper.EmptyInt);
                }
            }

            if (sname.Starts != null)
            {
                List <IIterator> enumerators = new List <IIterator>();

                foreach (var nameId in _storage.StartWith(sname.Starts))
                {
                    var list = _byName.GetValueOrDefault(nameId);
                    if (list != null)
                    {
                        enumerators.Add(list.GetIterator());
                    }
                }

                return(enumerators.MergeSort());
            }
            else if (sname.Eq != null)
            {
                return(_byName.GetValueOrDefault(_storage.Get(sname.Eq))?.GetIterator() ?? ListHelper.EmptyInt);
            }

            return(_ids.GetIterator());
        }
示例#23
0
        public IIterator FilterAny(List <string> any)
        {
            List <IIterator> enumerators = new List <IIterator>(any.Count);

            for (int i = 0; i < any.Count; i++)
            {
                var interestId = _storage.Get(any[i]);
                if (_id2AccId[interestId] != null)
                {
                    enumerators.Add(_id2AccId[interestId].GetIterator());
                }
            }

            return(enumerators.MergeSort().Distinct());
        }
示例#24
0
        /// <summary>
        /// 测试方法001
        /// </summary>
        public static void TestMergeSort001(List <Element> list, bool descending)
        {
            Console.WriteLine("Test: _MergeSort.cs 001");
            if (list == null)
            {
                Console.WriteLine("要排序的数列为null,无法排序。程序为求效率,没有进行数列为null的检验。");
                //Console.ReadLine();
            }
            List <Element> lstElement         = list;
            List <Element> lstOriginalElement = new List <Element>(lstElement.AsEnumerable());

            lstElement.MergeSort(descending);
            Tools.testError(lstElement, lstOriginalElement, descending);
            Console.WriteLine();
        }
        static void Main(string[] args)
        {
            Random rnd = new Random();

            for (int i = 0; i < 3000000; i++)
            {
                list.Add(rnd.Next());
            }

            TestAlgorithm("heap", list => list.HeapSort());
            TestAlgorithm("merge", list => list.MergeSort());
            TestAlgorithm("quick", list => list.QuickSort());
            TestAlgorithm("sort", list => list.Sort());

            Console.ReadKey();
        }
示例#26
0
        public void MergeSort_EmptyArray_DontBreakDown()
        {
            List <int> arrayIn   = new List <int>();
            bool       breakDown = false;

            try
            {
                arrayIn.MergeSort();
            }
            catch (Exception e)
            {
                breakDown = true;
                TestContext.WriteLine(e.ToString());
            }

            Assert.IsFalse(breakDown);
        }
示例#27
0
        public void MergeSort_RandomUnorderedWithReverseComparerIn_ReverseOrderedOut()
        {
            List <int> arrayIn   = new List <int>();
            Random     randomGen = new Random(DateTime.Now.GetHashCode());

            for (int i = 0; i < TestSettings.Count; i++)
            {
                arrayIn.Add(randomGen.Next() % TestSettings.MaxRandomGeneratedValue);
            }

            List <int> arrayInCopy = new List <int>(arrayIn);

            arrayIn.MergeSort((x, y) => y - x);
            arrayInCopy.Sort((x, y) => y - x);

            CollectionAssert.AreEqual(arrayIn, arrayInCopy);
        }
示例#28
0
        public override ObjectData GetData(NodeFactory factory, bool relocsOnly = false)
        {
            ObjectDataBuilder builder = new ObjectDataBuilder(factory, relocsOnly);

            builder.RequireInitialPointerAlignment();
            builder.AddSymbol(this);

            EmitHeaderPrefix(ref builder);

            // Don't bother sorting if we're not emitting the contents
            if (!relocsOnly)
            {
                _items.MergeSort((x, y) => Comparer <int> .Default.Compare((int)x.Id, (int)y.Id));
            }

            // ReadyToRunHeader.Flags
            builder.EmitInt((int)_flags);

            // ReadyToRunHeader.NumberOfSections
            ObjectDataBuilder.Reservation sectionCountReservation = builder.ReserveInt();

            int count = 0;

            foreach (var item in _items)
            {
                // Skip empty entries
                if (!relocsOnly && item.Node.ShouldSkipEmittingObjectNode(factory))
                {
                    continue;
                }

                builder.EmitInt((int)item.Id);

                builder.EmitReloc(item.StartSymbol, RelocType.IMAGE_REL_BASED_ADDR32NB);
                builder.EmitReloc(item.StartSymbol, RelocType.IMAGE_REL_SYMBOL_SIZE);

                count++;
            }

            builder.EmitInt(sectionCountReservation, count);

            return(builder.ToObjectData());
        }
示例#29
0
        public void MergeSort_Should_Sort_Hard()
        {
            var random = new System.Random();

            IList <int> randomNumbers = new List <int>();;

            const int LIMIT = 100;

            for (int i = 0; i < LIMIT; i++)
            {
                randomNumbers.Add(random.Next(0, 100));
            }

            randomNumbers = randomNumbers.OrderBy(i => i).ToList();

            var test = randomNumbers.MergeSort();

            Assert.That(test, Is.EqualTo(randomNumbers));
        }
示例#30
0
        static void Main ( string[] args )
        {
            List<int> array = new List<int>() { 2 , 4 , 1 , 6 , 10 };
            Console.WriteLine(array.BinarySearch(10 , Comparer<int>.Default));

            List<int> sortedArrayBS = array.BubbleSort<int>(Comparer<int>.Default).ToList();
            List<int> sortedArraySS = array.SelectionSort<int>(Comparer<int>.Default).ToList();
            List<int> sortedArrayMS = array.MergeSort<int>(Comparer<int>.Default).ToList();
            List<int> sortedArrayQS = array.QuickSort<int>(Comparer<int>.Default).ToList();

            Console.Write("Original array: " + array.Count + "\n ");
            foreach(var item in array)
            {
                Console.Write(item + " ");
            }
            Console.WriteLine();
            Console.Write("Bubble Sort: ");
            foreach(var item in sortedArrayBS)
            {
                Console.Write(item + " ");
            }
            Console.WriteLine();
            Console.Write("Selection Sort: ");
            foreach(var item in sortedArraySS)
            {
                Console.Write(item + " ");
            }
            Console.WriteLine();
            Console.Write("Merge Sort: ");
            foreach(var item in sortedArrayMS)
            {
                Console.Write(item + " ");
            }
            Console.WriteLine();
            Console.Write("Quick Sort: ");
            foreach(var item in sortedArrayQS)
            {
                Console.Write(item + " ");
            }
            Console.WriteLine();
            Console.ReadKey();
        }
示例#31
0
        public void SortingARangeOfItemsInAscendingOrderAndCheckingIfSorted()
        {
            var list = new List <int>();

            int minElement = -50000;
            int maxElement = 50000;

            int addedElements = 0;

            //Adding every seventh number, then every fifth number,
            //every third and at last all numbers
            //NOTE: some items are added more than once
            for (int i = 7; i > 0; i -= 2)
            {
                int el = minElement;
                while (el <= maxElement)
                {
                    list.Add(el);
                    addedElements++;
                    el += i;
                }
            }

            int beginSortAt = addedElements / 3;
            int sortedCount = addedElements / 2;

            list.MergeSort(beginSortAt, sortedCount, null);

            var last = int.MinValue;

            for (int i = beginSortAt; i < beginSortAt + sortedCount; i++)
            {
                if (last > list[i])
                {
                    Assert.Fail();
                }

                last = list[i];
            }
        }
示例#32
0
        public override ObjectData GetData(NodeFactory factory, bool relocsOnly)
        {
            ObjectDataBuilder builder = new ObjectDataBuilder(factory, relocsOnly);

            builder.RequireInitialPointerAlignment();

            if (_sorter != null)
            {
                _nestedNodesList.MergeSort(_sorter);
            }

            builder.AddSymbol(StartSymbol);

            GetElementDataForNodes(ref builder, factory, relocsOnly);

            EndSymbol.SetSymbolOffset(builder.CountBytes);
            builder.AddSymbol(EndSymbol);

            ObjectData objData = builder.ToObjectData();

            return(objData);
        }
示例#33
0
        public void SortingInAscendingOrderUsingAComparisonAndCheckingIfSorted()
        {
            var list = new List <int>();

            int minElement = -50000;
            int maxElement = 50000;

            int addedElements = 0;

            //Adding every seventh number, then every fifth number,
            //every third and at last all numbers
            //NOTE: some items are added more than once
            for (int i = 7; i > 0; i -= 2)
            {
                int el = minElement;
                while (el <= maxElement)
                {
                    list.Add(el);
                    addedElements++;
                    el += i;
                }
            }

            list.MergeSort((x, y) => x.CompareTo(y));

            var last = int.MinValue;

            foreach (var item in list)
            {
                if (last > item)
                {
                    Assert.Fail();
                }

                last = item;
            }
        }
示例#34
0
        public IIterator Filter(FilterRequest.StatusRequest status)
        {
            if (status.Eq == status.Neq)
            {
                return(ListHelper.EmptyInt);
            }

            if (status.Eq != null)
            {
                return(_groups[(int)status.Eq.Value].GetIterator());
            }

            List <IIterator> enumerators = new List <IIterator>(2);

            for (int i = 0; i < 3; i++)
            {
                if (i == (int)status.Neq)
                {
                    continue;
                }
                enumerators.Add(_groups[i].GetIterator());
            }
            return(enumerators.MergeSort());
        }
示例#35
0
 static void Main(string[] args)
 {
     IList<int> array = new List<int> { 5, 2, 1, 4, 3 };
     IList<int> sorted = array.MergeSort<int>(Comparer<int>.Default);
    // Console.WriteLine(index);
 }
示例#36
0
        static void Main(string[] args)
        {
            while (true)
            {
                Console.Write("------------\nElements: ");
                int n = Convert.ToInt32(Console.ReadLine());
                Console.WriteLine("------------");
                var sortme = new List<int>();
                var orderme = new List<Foo>();
                DateTime startTime;

                Random randNum = new Random();
                IReadOnlyList<int> li = Enumerable.Repeat(0, n).Select(i => randNum.Next(0, 500)).ToArray();

                Console.WriteLine("\n** Sort items by value **\n");

                sortme = new List<int>(li);
                startTime = DateTime.Now;
                sortme.BubbleSort();
                Console.WriteLine("Bubble took: {0} ms", (DateTime.Now - startTime).TotalMilliseconds);

                sortme = new List<int>(li);
                startTime = DateTime.Now;
                sortme.InsertionSort();
                Console.WriteLine("Insertion took: {0} ms", (DateTime.Now - startTime).TotalMilliseconds);

                sortme = new List<int>(li);
                startTime = DateTime.Now;
                sortme.SelectionSort();
                Console.WriteLine("Selection took: {0} ms", (DateTime.Now - startTime).TotalMilliseconds);

                sortme = new List<int>(li);
                startTime = DateTime.Now;
                sortme.HeapSort();
                Console.WriteLine("Heap took: {0} ms", (DateTime.Now - startTime).TotalMilliseconds);

                sortme = new List<int>(li);
                startTime = DateTime.Now;
                sortme.MergeSort();
                Console.WriteLine("Merge took: {0} ms", (DateTime.Now - startTime).TotalMilliseconds);

                Console.WriteLine();

                Console.WriteLine("\n** Sort items by key **\n");

                IReadOnlyList<Foo> list = new List<int>(li).ConvertAll(x => new Foo { bar = x });

                orderme = new List<Foo>(list);
                startTime = DateTime.Now;
                orderme.BubbleSort(x => x.bar);
                Console.WriteLine("Bubble took: {0} ms", (DateTime.Now - startTime).TotalMilliseconds);

                orderme = new List<Foo>(list);
                startTime = DateTime.Now;
                orderme.InsertionSort(x => x.bar);
                Console.WriteLine("Insertion took: {0} ms", (DateTime.Now - startTime).TotalMilliseconds);

                orderme = new List<Foo>(list);
                startTime = DateTime.Now;
                orderme.SelectionSort(x => x.bar);
                Console.WriteLine("Selection took: {0} ms", (DateTime.Now - startTime).TotalMilliseconds);

                orderme = new List<Foo>(list);
                startTime = DateTime.Now;
                orderme.HeapSort(x => x.bar);
                Console.WriteLine("Heap took: {0} ms", (DateTime.Now - startTime).TotalMilliseconds);

                orderme = new List<Foo>(list);
                startTime = DateTime.Now;
                orderme.MergeSort(x => x.bar);
                Console.WriteLine("Merge took: {0} ms", (DateTime.Now - startTime).TotalMilliseconds);

                Console.WriteLine();
            }
        }
示例#37
0
        static unsafe void Main(string[] args)
        {
            /*Consistency benkmark.*/
            Console.WriteLine("Consistency benchmarking...");
            List<int> consistencyList1 = new List<int>() { 13, 3, 1, 0, 11, 4, 12, 1 };
            List<int> consistencyList2 = new List<int>(consistencyList1);
            List<int> consistencyList3 = new List<int>(consistencyList1);
            List<int> consistencyList4 = new List<int>(consistencyList1);
            List<int> consistencyList5 = new List<int>(consistencyList1);

            Console.WriteLine("Quick Sort:");
            consistencyList1.QuickSort();
            foreach(int val in consistencyList1)
            {
                if (consistencyList1.IndexOf(val) != consistencyList1.Count-1)
                {
                    Console.Write(val + ",");
                }

                else
                {
                    Console.WriteLine(val);
                }

            }

            Console.WriteLine();

            Console.WriteLine("Insertion Sort:");
            consistencyList2.InsertionSort();
            foreach (int val in consistencyList2)
            {
                if (consistencyList2.IndexOf(val) != consistencyList2.Count - 1)
                {
                    Console.Write(val + ",");
                }

                else
                {
                    Console.WriteLine(val);
                }

            }

            Console.WriteLine();

            Console.WriteLine("Bubble Sort:");
            consistencyList3.BubbleSort();
            foreach (int val in consistencyList3)
            {
                if (consistencyList3.IndexOf(val) != consistencyList3.Count - 1)
                {
                    Console.Write(val + ",");
                }

                else
                {
                    Console.WriteLine(val);
                }

            }

            Console.WriteLine();

            Console.WriteLine("Merge Sort:");
            consistencyList4.MergeSort();
            foreach (int val in consistencyList4)
            {
                if (consistencyList4.IndexOf(val) != consistencyList4.Count - 1)
                {
                    Console.Write(val + ",");
                }

                else
                {
                    Console.WriteLine(val);
                }

            }

            Console.WriteLine();

            Console.WriteLine("Heap Sort:");
            consistencyList5.HeapSort();
            foreach (int val in consistencyList5)
            {
                if (consistencyList5.IndexOf(val) != consistencyList5.Count - 1)
                {
                    Console.Write(val + ",");
                }

                else
                {
                    Console.WriteLine(val);
                }

            }

            Console.WriteLine();

            /*Time Benchmark*/
            int numVal = 15000;
            Console.WriteLine("Time benchmarking..." + numVal + " values");
            List<int> myNewList = new List<int>();

            Random randomizer = new Random();

            for (int i = 0; i < numVal;i++)
            {
                myNewList.Add(randomizer.Next(0, 20000));
            }

            List<int> myNewList1 = new List<int>(myNewList);
            List<int> myNewList2 = new List<int>(myNewList);
            List<int> myNewList3 = new List<int>(myNewList);
            List<int> myNewList4 = new List<int>(myNewList);
            List<int> myNewList5 = new List<int>(myNewList);

            //sort by default
            var watchDefault = System.Diagnostics.Stopwatch.StartNew();
            myNewList.Sort();
            watchDefault.Stop();
            Console.WriteLine("Default CLR sort: " + watchDefault.ElapsedMilliseconds + " ms");

            //sort by custom quick
            watchDefault.Restart();
            myNewList1.QuickSort();
            watchDefault.Stop();
            Console.WriteLine("Custom Quick sort: " + watchDefault.ElapsedMilliseconds + " ms");

            //sort by custom insertion
            watchDefault.Restart();
            myNewList2.InsertionSort();
            watchDefault.Stop();
            Console.WriteLine("Custom Insertion sort: " + watchDefault.ElapsedMilliseconds + " ms");

            //sort by custom bubble
            watchDefault.Restart();
            myNewList3.BubbleSort();
            watchDefault.Stop();
            Console.WriteLine("Custom Bubble sort: " + watchDefault.ElapsedMilliseconds + " ms");

            //sort by custom merge
            watchDefault.Restart();
            myNewList4.MergeSort();
            watchDefault.Stop();
            Console.WriteLine("Custom Merge sort: " + watchDefault.ElapsedMilliseconds + " ms");

            //sort by custom heap
            watchDefault.Restart();
            myNewList5.HeapSort();
            watchDefault.Stop();
            Console.WriteLine("Custom Heap sort: " + watchDefault.ElapsedMilliseconds + " ms");

            //done
            Console.WriteLine("Done!");

            //default pause
            Console.ReadLine();
        }