コード例 #1
0
        public void QuickSortTest()
        {
            List <int> unsorted = new List <int>();
            List <int> sorted;
            Random     random = new Random();

            for (int i = 0; i < 2000000; i++)
            {
                unsorted.Add(random.Next(1, 2000000));
            }
            Stopwatch stopwatch = new Stopwatch();

            stopwatch.Start();
            sorted = _object.QuickSort(unsorted);
            stopwatch.Stop();
            string totaltime = stopwatch.Elapsed.ToString();

            Assert.AreEqual(sorted.Count, unsorted.Count);

            /*
             * 20,000  -00:00:00.0076616
             * 2,00,000-00:00:00.0455105
             * 20,00,000-00:00:00.9556085
             */
        }
コード例 #2
0
        public void QuickSortTest()
        {
            SortingAlgorithms <int> .QuickSort(_Items);

            string tmp = string.Join(",", _Items);

            Assert.AreEqual(tmp, _ExpectedResult);
        }
コード例 #3
0
        public void Can_QuickSort()
        {
            int[] expect = { 4, 5, 2, 3, 3, 6, 7, -1, 0, -1 };
            int[] sorted = { -1, -1, 0, 2, 3, 3, 4, 5, 6, 7 };

            SortingAlgorithms <int> .QuickSort(expect, Comparer <int> .Default, 0, expect.Length);

            CollectionAssert.AreEqual(sorted, expect);
        }
コード例 #4
0
        public void QuickSortTest()
        {
            sorter.QuickSort(arr);

            for (int i = 0; i < arr.Length - 1; i++)
            {
                Assert.True(arr[i] <= arr[i + 1]);
            }
        }
コード例 #5
0
        public void Can_QuickSort_Work_On_Big_Arrays()
        {
            byte[] array = new byte[10000];
            new Random().NextBytes(array);

            SortingAlgorithms <byte> .QuickSort(array);

            for (int i = 1; i < array.Length; i++)
            {
                Assert.IsTrue(array[i - 1] <= array[i]);
            }
        }
コード例 #6
0
        public void QuickSortTest()
        {
            //Arrange
            int[] unsorted = new int[] { 9, 1, 5, 2, 4, 0 };
            int[] expected = new int[] { 0, 1, 2, 4, 5, 9 };

            //Act
            SortingAlgorithms.QuickSort(unsorted);

            //Assert
            CollectionAssert.AreEqual(expected, unsorted);
        }
コード例 #7
0
        public void TestQuickSort()
        {
            // Arrange
            int[] arr      = new int[] { 4, 10, 2, 1, 8, 9, 5, 7, 6, 3 };
            int[] expected = new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };

            // Act
            SortingAlgorithms.QuickSort(arr);
            foreach (int i in arr)
            {
                Console.WriteLine(i);
            }

            // Assert
            CollectionAssert.AreEqual(expected, arr);
        }
コード例 #8
0
        private static void StringSorting()
        {
            string[] arrayToSort = new string[] { "hehe", "wow", "isurual", "whatIf", "isRael", "isnt", "rael", "huh", "whaddaboutdat", "tahtsIT", "noMoreStrings" };
            Logger.Log("String array sorting");

            TimeTracker.MeasureTime("Insertion sort", () =>
            {
                SortingAlgorithms.InsertionSort(arrayToSort);
            });

            TimeTracker.MeasureTime("Selection sort", () =>
            {
                SortingAlgorithms.SelectionSort(arrayToSort);
            });

            TimeTracker.MeasureTime("Quick sort", () =>
            {
                SortingAlgorithms.QuickSort(arrayToSort, 0, arrayToSort.Length - 1);
            });
        }
コード例 #9
0
        private static void IntSorting()
        {
            GenerateArray(213, 8743267);

            Console.WriteLine("Int array sorting");

            TimeTracker.MeasureTime("Insertion sort", () =>
            {
                SortingAlgorithms.InsertionSort(arrayToSort);
            });

            TimeTracker.MeasureTime("Selection sort", () =>
            {
                SortingAlgorithms.SelectionSort(arrayToSort);
            });

            TimeTracker.MeasureTime("Quick sort", () =>
            {
                SortingAlgorithms.QuickSort(arrayToSort, 0, arrayToSort.Length - 1);
            });
        }
コード例 #10
0
        private static void DoubleSorting()
        {
            var arrayToSort = RandomArrayGenerator.GenerateDoubleArray(-30, 23242342);

            Logger.Log("Double array sorting");

            TimeTracker.MeasureTime("Insertion sort", () =>
            {
                SortingAlgorithms.InsertionSort(arrayToSort);
            });

            TimeTracker.MeasureTime("Selection sort", () =>
            {
                SortingAlgorithms.SelectionSort(arrayToSort);
            });

            TimeTracker.MeasureTime("Quick sort", () =>
            {
                SortingAlgorithms.QuickSort(arrayToSort, 0, arrayToSort.Length - 1);
            });
        }
コード例 #11
0
        private static void DoubleSorting()
        {
            var array = GenerateArray(132, 783245238)
                        .Select(x => (double)(x + 1.01))
                        .ToArray();

            Console.WriteLine("Double array sorting");

            TimeTracker.MeasureTime("Insertion sort", () =>
            {
                SortingAlgorithms.InsertionSort(arrayToSort);
            });

            TimeTracker.MeasureTime("Selection sort", () =>
            {
                SortingAlgorithms.SelectionSort(arrayToSort);
            });

            TimeTracker.MeasureTime("Quick sort", () =>
            {
                SortingAlgorithms.QuickSort(arrayToSort, 0, arrayToSort.Length - 1);
            });
        }
コード例 #12
0
    public static string[] ComputeArrayWithoutDelegate(string[] data, SortingTypes sortingType)
    {
        // Do some stuff on the array

        // Order the array
        switch (sortingType)
        {
        case SortingTypes.BubbleSort:
            data = SortingAlgorithms.BubbleSort(data);
            break;

        case SortingTypes.QuickSort:
            data = SortingAlgorithms.QuickSort(data);
            break;

        case SortingTypes.InsertionSort:
            data = SortingAlgorithms.InsertionSort(data);
            break;
        }

        // Do other stuff on the array

        return(data);
    }
コード例 #13
0
        static void Main(string[] args)
        {
            #region Design Patterns
            #region Decorator Pattern Example
            Espresso beverage1 = new Espresso();
            Console.WriteLine("Double Mocha Esspresso");
            Mocha d1 = new Mocha(beverage1);
            Mocha d2 = new Mocha(d1);
            Console.WriteLine(d2.Cost() + " " + d2.Description);

            Console.WriteLine("\n House Blend, Moch, Whip");
            HouseBlend beverage2 = new HouseBlend();
            Mocha      d3        = new Mocha(beverage2);
            Whip       d4        = new Whip(d3);
            Console.WriteLine(d4.Cost() + " " + d4.Description);
            #endregion

            #region Factory Pattern
            // Note: constructors call Factory Method
            Document[] documents = new Document[2];

            documents[0] = new Resume();
            documents[1] = new Report();

            // Display document pages
            foreach (Document document in documents)
            {
                Console.WriteLine("\n" + document.GetType().Name + "--");
                foreach (Page page in document.Pages)
                {
                    Console.WriteLine(" " + page.GetType().Name);
                }
            }
            #endregion

            #region Abstract Factory Pattern
            ContinentFactory africa = new AfricaFactory();
            AnimalWorld      world  = new AnimalWorld(africa);
            world.RunFoodChain();

            ContinentFactory america = new AmericaFactory();
            world = new AnimalWorld(america);
            world.RunFoodChain();
            #endregion

            #region Singleton
            Console.WriteLine(Singleton.Math.Instance.add(34, 3));
            #endregion

            #region Obsever Pattern
            BaggageHandler  provider  = new BaggageHandler();
            ArrivalsMonitor observer1 = new ArrivalsMonitor("BaggageClaimMonitor1");
            ArrivalsMonitor observer2 = new ArrivalsMonitor("SecurityExit");

            provider.BaggageStatus(712, "Detroit", 3);
            observer1.Subscribe(provider);
            provider.BaggageStatus(712, "Kalamazoo", 3);
            provider.BaggageStatus(400, "New York-Kennedy", 1);
            provider.BaggageStatus(712, "Detroit", 3);
            observer2.Subscribe(provider);
            provider.BaggageStatus(511, "San Francisco", 2);
            provider.BaggageStatus(712);
            observer2.Unsubscribe();
            provider.BaggageStatus(400);
            provider.LastBaggageClaimed();
            #endregion

            #region Strategy Pattern
            SortedList studentRecords = new SortedList();
            studentRecords.Add("samual");
            studentRecords.Add("Jimmy");
            studentRecords.Add("Sandra");
            studentRecords.Add("Vivek");
            studentRecords.Add("Anna");

            studentRecords.SetSortStrategy(new QuickSort());
            studentRecords.Sort();

            studentRecords.SetSortStrategy(new ShellSort());
            studentRecords.Sort();

            studentRecords.SetSortStrategy(new MergeSort());
            studentRecords.Sort();
            #endregion

            #region Composite Pattern
            CompositeElement root = new CompositeElement("Picture");
            root.Add(new PrimitiveElement("Red Line"));
            root.Add(new PrimitiveElement("Blue Circle"));
            root.Add(new PrimitiveElement("Green Box"));

            CompositeElement comp = new CompositeElement("Two Circles");
            comp.Add(new PrimitiveElement("Black Circle"));
            comp.Add(new PrimitiveElement("White Circle"));
            root.Add(comp);

            PrimitiveElement pe = new PrimitiveElement("Yellow Line");
            root.Add(pe);
            root.Remove(pe);

            root.Display(1);
            #endregion

            #region Command Pattern
            User user = new User();

            user.Compute('+', 100);
            user.Compute('-', 50);
            user.Compute('*', 10);
            user.Compute('/', 2);

            user.Undo(4);
            user.Redo(3);
            #endregion

            #region COR (Chain of Responsibility)
            // Setup Chain of Responsibility
            Handler h1 = new ConcreteHandlerA();
            Handler h2 = new ConcreteHandlerB();
            Handler h3 = new ConcreteHandlerC();
            h2.SetSuccessor(h3);
            h1.SetSuccessor(h2);


            // Generate and process request
            int[] requests = { 2, 5, 14, 22, 18, 3, 27, 20 };

            foreach (int request in requests)
            {
                h1.HandleRequest(request);
            }
            #endregion

            #endregion

            #region AD

            #region List
            MyArrayList list = new MyArrayList(5);
            //setting values
            list.add(1);
            list.add(2);
            list.add(3);
            list.add(4);
            list.add(5);

            Console.WriteLine(list.get(2) + " staat op positie 2");
            //testing print function
            list.print();
            //testing set function
            list.set(2, 10); //true
            list.print();
            list.set(10, 2); //false
            //occurences test
            list.set(0, 2);
            list.set(4, 2);
            list.countOccurences(2);
            //testing clear
            list.clear();
            list.print();

            MyLinkedList <int> linkedList = new MyLinkedList <int>();
            linkedList.addFirst(1);
            linkedList.addFirst(12);
            linkedList.addFirst(3);
            linkedList.addFirst(4);
            linkedList.addFirst(5);
            linkedList.insert(0, 123);
            linkedList.remove(12);
            MyLinkedList <int> .printList(linkedList);

            Console.ReadLine();
            #endregion

            #region Graph
            Graph g = new Graph();

            try
            {
                StreamReader d = new StreamReader(Console.ReadLine());
                string       line;
                while ((line = d.ReadLine()) != null)
                {
                    Console.WriteLine(line);
                    string[] words = line.Split(' ');
                    try
                    {
                        if (words.Length > 3)
                        {
                            Console.WriteLine("Skipping bad line: " + line);
                            continue;
                        }
                        string source = words[0];
                        string dest   = words[1];
                        int    cost   = Int32.Parse(words[2]);

                        g.addEdge(source, dest, cost);
                    }
                    catch (FormatException e)
                    {
                        Console.WriteLine("Skipping bad line: " + line);
                        Console.WriteLine(e);
                    }
                }
            }
            catch (Exception e) { Console.WriteLine(e); }


            //while (processRequest(g));
            #endregion

            #region Binairy tree
            string seperator = "-----------------------------------------------------------------------";
            Console.WriteLine(seperator);
            Console.WriteLine("Binary Tree Basic: ");
            BinaryNode <int> NodeA = new BinaryNode <int>(2);
            BinaryNode <int> NodeB = new BinaryNode <int>(5);
            BinaryNode <int> NodeC = new BinaryNode <int>(6);
            BinaryNode <int> NodeD = new BinaryNode <int>(3);
            BinaryNode <int> NodeE = new BinaryNode <int>(7);
            BinaryNode <int> NodeF = new BinaryNode <int>(10);
            BinaryNode <int> NodeG = new BinaryNode <int>(1);

            NodeE.setRight(NodeG);

            NodeA.setLeft(NodeC);
            NodeA.setRight(NodeD);

            NodeB.setLeft(NodeE);
            NodeB.setRight(NodeF);


            BinaryTree <int> tree = new BinaryTree <int>(12);
            tree.Root.setLeft(NodeA);
            tree.Root.setRight(NodeB);

            tree.printPreOrder();
            Console.ReadLine();

            Console.WriteLine(seperator);
            Console.WriteLine("Binary Search Tree: ");
            BinaryTree <int> BST = new BinaryTree <int>();
            BST.Insert(5);
            BST.Insert(1254);
            BST.Insert(252);
            BST.Insert(378);
            BST.Insert(45);

            BST.Insert(668);
            BST.Insert(71);
            BST.Insert(8);
            BST.Insert(942);
            //fail test
            BST.Insert(1);

            Console.WriteLine(seperator);
            Console.WriteLine("Printing in order: ");
            BST.printInOrder();
            Console.ReadLine();

            Console.WriteLine(seperator);
            Console.WriteLine("Finding Min:");
            Console.WriteLine(BST.FindMin());
            Console.ReadLine();

            Console.WriteLine(seperator);
            Console.WriteLine("Finding Max: ");
            Console.WriteLine(BST.FindMax());
            Console.ReadLine();

            Console.WriteLine(seperator);
            Console.WriteLine("Finding value 5:");
            Console.WriteLine(BST.Find(5));
            Console.ReadLine();

            Console.WriteLine(seperator);
            Console.WriteLine("Removing 5");
            BST.Remove(5);
            Console.ReadLine();

            Console.WriteLine(seperator);
            Console.WriteLine("Printing in order: ");
            BST.printInOrder();
            Console.ReadLine();

            Console.WriteLine(seperator);
            Console.WriteLine("Removing Min");
            BST.RemoveMin();
            Console.ReadLine();

            Console.WriteLine(seperator);
            Console.WriteLine("Printing in order: ");
            BST.printInOrder();
            Console.ReadLine();
            #endregion

            #region Max heap
            MaxHeap theHeap = new MaxHeap(21);
            theHeap.Insert(40);
            theHeap.Insert(70);
            theHeap.Insert(20);
            theHeap.Insert(60);
            theHeap.Insert(50);
            theHeap.Insert(100);
            theHeap.Insert(82);
            theHeap.Insert(35);
            theHeap.Insert(90);
            theHeap.Insert(10);
            theHeap.DisplayHeap();

            Console.WriteLine("Inserting a new node with value 120");
            theHeap.Insert(120);
            theHeap.DisplayHeap();

            Console.WriteLine("Removing max element");
            theHeap.Remove();
            theHeap.DisplayHeap();

            Console.WriteLine("Changing root to 130");
            theHeap.HeapIncreaseDecreaseKey(0, 130);
            theHeap.DisplayHeap();

            Console.WriteLine("Changing root to 5");
            theHeap.HeapIncreaseDecreaseKey(0, 5);
            theHeap.DisplayHeap();
            Console.ReadLine();
            #endregion

            #region Min heap
            int[] arrA = { 50, 2, 30, 7, 40, 4, 10, 16, 12 };
            Console.WriteLine("Original Array : ");
            for (int i = 0; i < arrA.Length; i++)
            {
                Console.Write("  " + arrA[i]);
            }
            MinHeap m = new MinHeap(arrA.Length);
            Console.WriteLine("\nMin-Heap : ");
            m.createHeap(arrA);
            m.display();
            Console.WriteLine("Extract Min :");
            for (int i = 0; i < arrA.Length; i++)
            {
                Console.Write("  " + m.extractMin());
            }
            #endregion

            #region Sorting
            Console.WriteLine();
            int[] tmpArray = { 0, 15, 48, 60, 88, 123, 1, 5, 4, 12, 99, 11, 200, 41 };
            Console.WriteLine(seperator);
            Console.WriteLine("Base Array: ");
            SortingAlgorithms.Show_array_elements(tmpArray);
            Console.WriteLine(seperator);
            var watch = System.Diagnostics.Stopwatch.StartNew();
            SortingAlgorithms.ShellSort(tmpArray);
            watch.Stop();
            var elapsedMs = watch.ElapsedMilliseconds;
            Console.WriteLine("Shell sorted Array in: " + elapsedMs + "ms");
            SortingAlgorithms.Show_array_elements(tmpArray);
            Console.WriteLine(seperator);
            Console.ReadKey();

            tmpArray = new[] { 0, 15, 48, 60, 88, 123, 1, 5, 4, 12, 99, 11, 200, 41 };
            Console.WriteLine("Base Array: ");
            SortingAlgorithms.Show_array_elements(tmpArray);
            Console.WriteLine(seperator);

            watch = System.Diagnostics.Stopwatch.StartNew();
            SortingAlgorithms.PerformInsertionSort(tmpArray);
            watch.Stop();
            elapsedMs = watch.ElapsedMilliseconds;
            Console.WriteLine("Insertion sorted Array in: " + elapsedMs + "ms");
            SortingAlgorithms.Show_array_elements(tmpArray);
            Console.WriteLine(seperator);
            Console.ReadKey();

            tmpArray = new[] { 0, 15, 48, 60, 88, 123, 1, 5, 4, 12, 99, 11, 200, 41 };
            Console.WriteLine("Base Array: ");
            SortingAlgorithms.Show_array_elements(tmpArray);
            Console.WriteLine(seperator);

            watch = System.Diagnostics.Stopwatch.StartNew();
            SortingAlgorithms.MergeSort(tmpArray);
            watch.Stop();
            elapsedMs = watch.ElapsedMilliseconds;
            Console.WriteLine("Merge sorted Array in: " + elapsedMs + "ms");
            SortingAlgorithms.Show_array_elements(tmpArray);
            Console.WriteLine(seperator);
            Console.ReadKey();

            tmpArray = new[] { 0, 15, 48, 60, 88, 123, 1, 5, 4, 12, 99, 11, 200, 41, 46 };
            Console.WriteLine("Base Array: ");
            SortingAlgorithms.Show_array_elements(tmpArray);
            Console.WriteLine(seperator);

            watch = System.Diagnostics.Stopwatch.StartNew();
            SortingAlgorithms.QuickSort(tmpArray, 0, tmpArray.Length - 1);
            watch.Stop();
            elapsedMs = watch.ElapsedMilliseconds;
            Console.WriteLine("Quick sorted Array in: " + elapsedMs + "ms");
            SortingAlgorithms.Show_array_elements(tmpArray);
            Console.WriteLine(seperator);
            Console.ReadKey();
            #endregion
            #endregion
            Console.ReadKey();
        }
コード例 #14
0
 public void QuickSort_Throws_ArgumentNullException()
 {
     SortingAlgorithms <int> .QuickSort(null, null, 0, 10);
 }
コード例 #15
0
        public static void Main(string[] args)
        {
            sa  = new SortingAlgorithms();
            n_5 = new int[1000000];
            n_6 = new int[10000000];
            rnd = new Random(8);  //Seed carefully chosen by the team

            for (int i = 0; i < n_6.Length; i++)
            {
                int nextRand = rnd.Next();

                n_6[i] = nextRand;
                if (i < n_5.Length)
                {
                    n_5[i] = nextRand;
                }
            }

            Console.WriteLine("Merge sort 10^5: ");

            for (int i = 0; i < 100; i++)
            {
                DateTime start = DateTime.Now;
                sa.MergeSort(n_5);
                DateTime end = DateTime.Now;
                Console.WriteLine(i + ") " + (end - start));
            }

            Console.WriteLine("Merge sort 10^6: ");

            for (int i = 0; i < 100; i++)
            {
                DateTime start = DateTime.Now;
                sa.MergeSort(n_6);
                DateTime end = DateTime.Now;
                Console.WriteLine(i + ") " + (end - start));
            }

            Console.WriteLine("Quick sort 10^5: ");

            for (int i = 0; i < 100; i++)
            {
                int[] copy = new int[n_5.Length];

                for (int j = 0; j < copy.Length; j++)
                {
                    copy[j] = n_5[j];
                }

                DateTime start = DateTime.Now;
                sa.QuickSort(copy);
                DateTime end = DateTime.Now;
                Console.WriteLine(i + ") " + (end - start));
            }

            Console.WriteLine("Quick sort 10^6: ");

            for (int i = 0; i < 100; i++)
            {
                int[] copy = new int[n_6.Length];

                for (int j = 0; j < copy.Length; j++)
                {
                    copy[j] = n_6[j];
                }

                DateTime start = DateTime.Now;
                sa.QuickSort(copy);
                DateTime end = DateTime.Now;
                Console.WriteLine(i + ") " + (end - start));
            }
        }