public void AddHaulDestination(IHaulDestination haulDestination)
        {
            if (allHaulDestinationsInOrder.Contains(haulDestination))
            {
                Log.Error("Double-added haul destination " + haulDestination.ToStringSafe());
                return;
            }
            allHaulDestinationsInOrder.Add(haulDestination);
            allHaulDestinationsInOrder.InsertionSort(CompareHaulDestinationPrioritiesDescending);
            ISlotGroupParent slotGroupParent = haulDestination as ISlotGroupParent;

            if (slotGroupParent == null)
            {
                return;
            }
            SlotGroup slotGroup = slotGroupParent.GetSlotGroup();

            if (slotGroup == null)
            {
                Log.Error("ISlotGroupParent gave null slot group: " + slotGroupParent.ToStringSafe());
                return;
            }
            allGroupsInOrder.Add(slotGroup);
            allGroupsInOrder.InsertionSort(CompareSlotGroupPrioritiesDescending);
            List <IntVec3> cellsList = slotGroup.CellsList;

            for (int i = 0; i < cellsList.Count; i++)
            {
                SetCellFor(cellsList[i], slotGroup);
            }
            map.listerHaulables.Notify_SlotGroupChanged(slotGroup);
            map.listerMergeables.Notify_SlotGroupChanged(slotGroup);
        }
        public List <WorkGiver> GetWorkGivers(bool emergency)
        {
            if (emergency && workGiversEmergencyCache != null)
            {
                return(workGiversEmergencyCache);
            }
            if (!emergency && workGiversNonEmergencyCache != null)
            {
                return(workGiversNonEmergencyCache);
            }

            List <WorkTypeDef> wtsByPrio             = new List <WorkTypeDef>();
            List <WorkTypeDef> allDefsListForReading = DefDatabase <WorkTypeDef> .AllDefsListForReading;
            int num = 999;

            for (int i = 0; i < allDefsListForReading.Count; i++)
            {
                WorkTypeDef workTypeDef = allDefsListForReading[i];
                int         priority    = GetPriority(workTypeDef);
                if (priority > 0)
                {
                    if (priority < num)
                    {
                        if (workTypeDef.workGiversByPriority.Any((WorkGiverDef wg) => wg.emergency == emergency))
                        {
                            num = priority;
                        }
                    }
                    wtsByPrio.Add(workTypeDef);
                }
            }
            wtsByPrio.InsertionSort(delegate(WorkTypeDef a, WorkTypeDef b)
            {
                float value = (float)(a.naturalPriority + (4 - this.GetPriority(a)) * 100000);
                return(((float)(b.naturalPriority + (4 - this.GetPriority(b)) * 100000)).CompareTo(value));
            });
            List <WorkGiver> workGivers = new List <WorkGiver>();

            for (int j = 0; j < wtsByPrio.Count; j++)
            {
                WorkTypeDef workTypeDef2 = wtsByPrio[j];
                for (int k = 0; k < workTypeDef2.workGiversByPriority.Count; k++)
                {
                    WorkGiver worker = workTypeDef2.workGiversByPriority[k].Worker;
                    workGivers.Add(worker);
                }
            }

            // Fill cache
            if (emergency)
            {
                workGiversEmergencyCache = workGivers;
            }
            else
            {
                workGiversNonEmergencyCache = workGivers;
            }

            return(workGivers);
        }
Ejemplo n.º 3
0
        public override void CallingSortOnAnEmptyListRemainsEmpty()
        {
            IList <int> empty = new List <int>();

            empty.InsertionSort();
            Assert.Empty(empty);
        }
    private bool SortByZ()     //returns true if the childNodes changed, false if they didn't
    {
        //using InsertionSort because it's stable (meaning equal values keep the same order)
        //this is unlike List.Sort, which is unstable, so things would constantly shift if equal.
        _childNodes.InsertionSort(ZComparison);

        //check if the order has changed, and if it has, update the quads/depth order
        //http://stackoverflow.com/questions/3030759/arrays-lists-and-computing-hashvalues-vb-c

        int hash = 269;

        unchecked         //don't throw int overflow exceptions
        {
            foreach (FNode node in _childNodes)
            {
                hash = (hash * 17) + node.GetHashCode();
            }
        }

        if (hash != _oldChildNodesHash)
        {
            _oldChildNodesHash = hash;
            return(true);            //order has changed
        }

        return(false);        //order hasn't changed
    }
Ejemplo n.º 5
0
        public void InsertionSort_ListGetsSorted()
        {
            // Test sorting by the integer key
            var actual_int = new List <int>(randList_int).ConvertAll(x => new MyClass {
                myInt = x
            });

            actual_int.InsertionSort(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.InsertionSort(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.InsertionSort(x => x.myStr);

            Assert.AreEqual(expected_str.Count, actual_str.Count);
            expected_str.Each((o, i) => Assert.AreEqual(o.myStr, actual_str[i].myStr));
        }
Ejemplo n.º 6
0
        static void Main(string[] args)
        {
            List <int> unsList = new List <int>
            {
                10,   // 0
                -1,   // 1
                8,    // 2
                15,   // 3
                23,   // 4
                -100, //5
                -16   //6
            };

            unsList.InsertionSort();

            //unsList.SelectionSort();

            //unsList.BubbleSort();

            List <char> charList = new List <char>
            {
                'z',
                'x',
                'a',
                'r',
                ' ',
                '/',
                '-'
            };

            charList.InsertionSort();
        }
Ejemplo n.º 7
0
 private bool SortByZ()     //returns true if the childNodes changed, false if they didn't
 {
     //using InsertionSort because it's stable (meaning equal values keep the same order)
     //this is unlike List.Sort, which is unstable, so things would constantly shift if equal.
     //note: it will only return true if the order changed
     return(_childNodes.InsertionSort(ZComparison));
 }
Ejemplo n.º 8
0
 public void Draw()
 {
     UpdateLists();
     draw.InsertionSort(drawOrder);
     for (int i = 0; i < draw.Count; i++)
     {
         draw[i].Draw();
     }
 }
Ejemplo n.º 9
0
 public void Update(float elapsedTime)
 {
     UpdateLists();
     update.InsertionSort(updateOrder);
     for (int i = 0; i < update.Count; i++)
     {
         update[i].Update(elapsedTime);
     }
 }
Ejemplo n.º 10
0
        public void InsertionSortTest()
        {
            Stopwatch timer = Stopwatch.StartNew();

            timer.Start();
            TestSet.InsertionSort();
            timer.Stop();
            Console.WriteLine("SORT TIME " + timer.ElapsedMilliseconds);
        }
Ejemplo n.º 11
0
        public void Test_InsertionSort()
        {
            var list = new List <int>()
            {
                4, 5, 1, 9, 2, 1, 7, 9, 64, 3
            };

            list.InsertionSort();
            Assert.True(list.IsSorted());
        }
Ejemplo n.º 12
0
        public static void Main(string[] args)
        {
            List <int> myl = new List <int>
            {
                6, 5, 6, 3, 7, 2, 0
            };

            myl.InsertionSort();
            myl.ShowAll();
        }
Ejemplo n.º 13
0
        public static bool CacheWorkGiversInOrder(Pawn_WorkSettings __instance)
        {
            //Pawn_WorkSettings.wtsByPrio.Clear();
            List <WorkTypeDef> wtsByPrio          = new List <WorkTypeDef>(); //ADD
            List <WorkTypeDef> defsListForReading = DefDatabase <WorkTypeDef> .AllDefsListForReading;
            int num1 = 999;

            for (int index = 0; index < defsListForReading.Count; ++index)
            {
                WorkTypeDef w        = defsListForReading[index];
                int         priority = __instance.GetPriority(w);
                if (priority > 0)
                {
                    if (priority < num1 && w.workGiversByPriority.Any(wg => !wg.emergency))
                    {
                        num1 = priority;
                    }
                    wtsByPrio.Add(w); //FIND REPLACE
                }
            }
            //FIND REPLACE
            wtsByPrio.InsertionSort((a, b) =>
            {
                float num2 = a.naturalPriority + (4 - __instance.GetPriority(a)) * 100000;
                return(((float)(b.naturalPriority + (4 - __instance.GetPriority(b)) * 100000)).CompareTo(num2));
            });
            WorkGiverListClear(workGiversInOrderEmerg(__instance));
            for (int index1 = 0; index1 < wtsByPrio.Count; ++index1) //FIND REPLACE
            {
                WorkTypeDef workTypeDef = wtsByPrio[index1];         ////FIND REPLACE
                for (int index2 = 0; index2 < workTypeDef.workGiversByPriority.Count; ++index2)
                {
                    WorkGiver worker = workTypeDef.workGiversByPriority[index2].Worker;
                    if (worker.def.emergency && __instance.GetPriority(worker.def.workType) <= num1)
                    {
                        WorkGiverListAdd(workGiversInOrderEmerg(__instance), worker);
                    }
                }
            }
            WorkGiverListClear(workGiversInOrderNormal(__instance));
            for (int index1 = 0; index1 < wtsByPrio.Count; ++index1) //FIND REPLACE
            {
                WorkTypeDef workTypeDef = wtsByPrio[index1];         //FIND REPLACE
                for (int index2 = 0; index2 < workTypeDef.workGiversByPriority.Count; ++index2)
                {
                    WorkGiver worker = workTypeDef.workGiversByPriority[index2].Worker;
                    if (!worker.def.emergency || __instance.GetPriority(worker.def.workType) > num1)
                    {
                        WorkGiverListAdd(workGiversInOrderNormal(__instance), worker);
                    }
                }
            }
            workGiversDirty(__instance) = false;
            return(false);
        }
Ejemplo n.º 14
0
        public void InsertionSort()
        {
            var list = new List <int> {
                3, 2, 6, 9, 3, 55, 123, 32
            };
            var expected = new List <int>(list);

            list.InsertionSort();
            expected.Sort();
            Assert.IsTrue(list.SequenceEqual(expected));
        }
Ejemplo n.º 15
0
        public void InsertionSortTest()
        {
            List <int> list = new List <int> {
                4, 2, 3, 1, 6, 7, 8, 9
            };

            list.InsertionSort();

            Assert.AreEqual(1, list[0]);
            Assert.AreEqual(9, list[list.Count - 1]);
        }
Ejemplo n.º 16
0
        public static void InsertionSort(List <int> myList, StreamWriter fisier = null, StreamWriter fisierValori = null)
        {
            Stopwatch sw = Stopwatch.StartNew();

            myList.InsertionSort();

            sw.Stop();

            fisier.WriteLine("Insertion Sort");
            fisierValori.WriteLine(sw.Elapsed);
        }
Ejemplo n.º 17
0
        public void InsertionSort_Should_Sort()
        {
            IList <int> numbers = new List <int> {
                2, 4, 1, 3
            };

            numbers = numbers.InsertionSort();

            Assert.That(numbers, Is.EqualTo(new List <int> {
                1, 2, 3, 4
            }));
        }
Ejemplo n.º 18
0
        private void CacheWorkGiversInOrder()
        {
            wtsByPrio.Clear();
            List <WorkTypeDef> allDefsListForReading = DefDatabase <WorkTypeDef> .AllDefsListForReading;
            int num = 999;

            for (int i = 0; i < allDefsListForReading.Count; i++)
            {
                WorkTypeDef workTypeDef = allDefsListForReading[i];
                int         priority    = GetPriority(workTypeDef);
                if (priority > 0)
                {
                    if (priority < num && workTypeDef.workGiversByPriority.Any((WorkGiverDef wg) => !wg.emergency))
                    {
                        num = priority;
                    }
                    wtsByPrio.Add(workTypeDef);
                }
            }
            wtsByPrio.InsertionSort(delegate(WorkTypeDef a, WorkTypeDef b)
            {
                float value = (float)(a.naturalPriority + (4 - GetPriority(a)) * 100000);
                return(((float)(b.naturalPriority + (4 - GetPriority(b)) * 100000)).CompareTo(value));
            });
            workGiversInOrderEmerg.Clear();
            for (int j = 0; j < wtsByPrio.Count; j++)
            {
                WorkTypeDef workTypeDef2 = wtsByPrio[j];
                for (int k = 0; k < workTypeDef2.workGiversByPriority.Count; k++)
                {
                    WorkGiver worker = workTypeDef2.workGiversByPriority[k].Worker;
                    if (worker.def.emergency && GetPriority(worker.def.workType) <= num)
                    {
                        workGiversInOrderEmerg.Add(worker);
                    }
                }
            }
            workGiversInOrderNormal.Clear();
            for (int l = 0; l < wtsByPrio.Count; l++)
            {
                WorkTypeDef workTypeDef3 = wtsByPrio[l];
                for (int m = 0; m < workTypeDef3.workGiversByPriority.Count; m++)
                {
                    WorkGiver worker2 = workTypeDef3.workGiversByPriority[m].Worker;
                    if (!worker2.def.emergency || GetPriority(worker2.def.workType) > num)
                    {
                        workGiversInOrderNormal.Add(worker2);
                    }
                }
            }
            workGiversDirty = false;
        }
        public void InsertionSort_ListComparer_SortedList()
        {
            foreach (var lst in Data.TestLists.Lists)
            {
                var expectedList = new List <int>(lst);
                expectedList.Sort();

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

                Assert.Equal(expectedList, testList);
            }
        }
Ejemplo n.º 20
0
        public void InsertionSort()
        {
            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.InsertionSort();

            Assert.Equal(expected, actual);
        }
Ejemplo n.º 21
0
        public static void DoTest()
        {
            var list1 = new ArrayList <int>
            {
                23,
                42,
                4,
                16,
                8,
                15,
                9,
                55,
                0,
                34,
                12,
                2
            };
            var list2 = new List <long>
            {
                23,
                42,
                4,
                16,
                8,
                15,
                9,
                55,
                0,
                34,
                12,
                2
            };

            // sort both lists
            list1.InsertionSort();
            list2.InsertionSort();

            bool isListEqual = true;

            for (int i = 0; i < list1.Count; i++)
            {
                if (list1[i] != list2[i])
                {
                    isListEqual = false;
                    break;
                }
            }

            Assert.True(isListEqual);
        }
Ejemplo n.º 22
0
        public void SortPrimitives()
        {
            List <int> li = new List <int> {
                1, 6, 2, 3, 8, 10, 9, 7, 4, 5
            };

            Assert.AreEqual(10, li.Count);

            li.InsertionSort();

            for (int i = 0; i < li.Count; i++)
            {
                Assert.AreEqual(i + 1, li[i]);
            }
        }
Ejemplo n.º 23
0
        /// <summary>
        /// 测试方法001
        /// </summary>
        public static void TestInsertionSort001(List <Element> list, bool descending)
        {
            Console.WriteLine("Test: _InsertionSort.cs 001");
            if (list == null)
            {
                Console.WriteLine("要排序的数列为null,无法排序。程序为求效率,没有进行数列为null的检验。");
                //Console.ReadLine();
            }
            List <Element> lstElement         = list;
            List <Element> lstOriginalElement = new List <Element>(lstElement.AsEnumerable());

            lstElement.InsertionSort(descending);
            Tools.testError(lstElement, lstOriginalElement, descending);
            Console.WriteLine();
        }
        public static void DoTest()
        {
            ArrayList <int> list = new ArrayList <int> ();

            list.Add(23);
            list.Add(42);
            list.Add(4);
            list.Add(16);
            list.Add(8);
            list.Add(15);
            list.Add(9);
            list.Add(55);
            list.Add(0);
            list.Add(34);
            list.Add(12);
            list.Add(2);

            Console.WriteLine("Before Sort:\r\n" + list.ToHumanReadable() + "\r\n");

            list.InsertionSort();

            Console.WriteLine("After Sort:\r\n" + list.ToHumanReadable() + "\r\n");


            // ANOTHER LIST TO SORT

            List <long> list2 = new List <long> ();

            list2.Add(23);
            list2.Add(42);
            list2.Add(4);
            list2.Add(16);
            list2.Add(8);
            list2.Add(15);
            list2.Add(9);
            list2.Add(55);
            list2.Add(0);
            list2.Add(34);
            list2.Add(12);
            list2.Add(2);

            list2.InsertionSort();
        }
Ejemplo n.º 25
0
        public void InsertionSort_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.OrderByDescending(i => i).ToList();

            var test = randomNumbers.InsertionSort();

            Assert.That(test, Is.EqualTo(randomNumbers));
        }
		public static void DoTest ()
		{
			ArrayList<int> list = new ArrayList<int> ();

			list.Add (23);
			list.Add (42);
			list.Add (4);
			list.Add (16);
			list.Add (8);
			list.Add (15);
			list.Add (9);
			list.Add (55);
			list.Add (0);
			list.Add (34);
			list.Add (12);
			list.Add (2);

			Console.WriteLine ("Before Sort:\r\n" + list.ToHumanReadable() + "\r\n");

			list.InsertionSort ();

			Console.WriteLine ("After Sort:\r\n" + list.ToHumanReadable() + "\r\n");


			// ANOTHER LIST TO SORT

			List<long> list2 = new List<long> ();

			list2.Add (23);
			list2.Add (42);
			list2.Add (4);
			list2.Add (16);
			list2.Add (8);
			list2.Add (15);
			list2.Add (9);
			list2.Add (55);
			list2.Add (0);
			list2.Add (34);
			list2.Add (12);
			list2.Add (2);

			list2.InsertionSort ();
		}
Ejemplo n.º 27
0
        public void SortingARangeOfItemsInAscendingOrderAndCheckingIfSorted()
        {
            var list = new List <int>();

            int minElement = -3000;
            int maxElement = 3000;

            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.InsertionSort(beginSortAt, sortedCount, null);

            var last = int.MinValue;

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

                last = list[i];
            }
        }
Ejemplo n.º 28
0
        public void SortingInAscendingOrderUsingAComparisonAndCheckingIfSorted()
        {
            var list = new List <int>();

            int minElement = -3000;
            int maxElement = 3000;

            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.InsertionSort((x, y) => x.CompareTo(y));

            var last = int.MinValue;

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

                last = item;
            }
        }
Ejemplo n.º 29
0
        public void Update(GameTime gameTime)
        {
            if (EnableInput && Visible
#if WINDOWS
                )
#else
                && !Guide.IsVisible)
#endif
            {
                foreach (var actor in actors)
                {
                    actor.Evaluate(gameTime, this);
                }
            }

            buffer.Clear();
            AddControlsToBuffer(Root);
            buffer.InsertionSort(ControlStrataComparer.BottomToTop);

            for (int i = 0; i < buffer.Count; i++)
            {
                buffer[i].Update(gameTime);
            }
        }
Ejemplo n.º 30
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();
            }
        }
Ejemplo n.º 31
0
 private void SortAreas()
 {
     areas.InsertionSort((Area a, Area b) => b.ListPriority.CompareTo(a.ListPriority));
 }
Ejemplo n.º 32
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();
            }
        }
Ejemplo n.º 33
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();
        }