示例#1
0
        public void TimedSelectionSortCompare()
        {
            var bSort = new BubbleSort<int>();
            var sSort = new SelectionSort<int>();

            Func<int[], SortOrder, int[]> bubSortFunc = bSort.Sort;
            Func<int[], SortOrder, int[]> selSortFunc = sSort.Sort;

            CompareSorts(bubSortFunc, selSortFunc);
        }
示例#2
0
        public void TimedBubbleSortCompare()
        {
            var bSort = new BubbleSort<int>();
            var ibSort = new ImprovedBubbleSort<int>();

            Func<int[], SortOrder, int[]> sortFunc = bSort.Sort;
            Func<int[], SortOrder, int[]> impSortFunc = ibSort.Sort;

            CompareSorts(sortFunc, impSortFunc);
        }
示例#3
0
 public void BasicSort()
 {
     var gen = new Random(44);
     var iSort = new BubbleSort<MockComparable>();
     foreach (var N in new[] { 1, 3, 5, 10 })
     {
         var mocks = Enumerable.Range(0, N).Select(i => new MockComparable(gen.Next(0, 10))).ToArray();
         iSort.Sort(mocks);
         Assert.IsTrue(mocks.IsSorted(), "#C" + N);
     }
 }
 public void TestInt()
 {
     BubbleSort<int> sortClass = new BubbleSort<int>();
     CompareInterface<int> comparator = new CompareInt();
     int[] array = new int[3];
     for (int i = 0; i < 3; ++i)
     {
         array[i] = i;
     }
     sortClass.BubbleSortFunction(comparator, ref array, 3);
     Assert.AreEqual(array[0], 2);
     Assert.AreEqual(array[1], 1);
     Assert.AreEqual(array[2], 0);
 }
 public void TestString()
 {
     BubbleSort<string> sortClass = new BubbleSort<string>();
     CompareInterface<string> comparator = new CompareString();
     string[] array = new string[3];
     for (int i = 0; i < 3; ++i)
     {
         array[i] = i.ToString();
     }
     sortClass.BubbleSortFunction(comparator, ref array, 3);
     Assert.AreEqual(array[0], "2");
     Assert.AreEqual(array[1], "1");
     Assert.AreEqual(array[2], "0");
 }
示例#6
0
        static void Main(string[] args)
        {
            int counter = 100;
            List<IComparable> values = new List<IComparable>();

            var random = new Random(DateTime.Now.Millisecond);
            for (int i = 0; i < counter; i++)
            {
                values.Add(new UserType(random.Next(0, 1000)));
            }

            var bubbleSort = new BubbleSort<IComparable, IList<IComparable>>();
            RunAlgorithm(values, bubbleSort);

            var shelllSort = new ShellSort<IComparable, IList<IComparable>>();
            RunAlgorithm(values, shelllSort);

            var quickSort = new QuickSort<IComparable, IList<IComparable>>();
            RunAlgorithm(values, quickSort);

            Console.ReadKey();
        }
示例#7
0
        public static Sorter displayMenu(Sorter aSorter)
        {
            Console.WriteLine("Select Options");
            Console.WriteLine("1- Bubble Sort");
            Console.WriteLine("2- Insertion Sort");
            Console.WriteLine("3- Quick Sort");
            String selectionString = Console.ReadLine();
            int InputNumber;
            int.TryParse(selectionString, out InputNumber);
            switch (InputNumber)
            {
                case 1:
                    aSorter = new BubbleSort();
                    break;
                case 2:
                    aSorter = new InsertionSort();
                    break;
                case 3:
                    aSorter = new QuickSort();
                    break;
            }

            return aSorter;
        }
示例#8
0
 private void Bs_FormClosed(object sender, FormClosedEventArgs e)
 {
     bs = null;
 }
示例#9
0
        static void Main(string[] args)
        {
            MyDatabase db = new MyDatabase();

            //======================================Linq (default=quicksort)=====================================

            //var shirts = db.Shirts.OrderBy(x => x.Color).ToList();
            //var shirts = db.Shirts.OrderBy(x => x.Size).ToList();
            //var shirts = db.Shirts.OrderBy(x => x.Fabric).ToList();
            //var shirts = db.Shirts.OrderByDescending(x => x.Fabric).ToList();
            //var shirts = db.Shirts.OrderBy(x => x.Size).ToList();
            // var shirts = db.Shirts.OrderBy(x => x.Color).ThenBy(x=>x.Size).ThenBy(x=>x.Fabric).ToList();

            //PrintAllItems(db.Shirts);

            // PrintAllItems(shirts); //me linq



            //================QuickSort===========================================

            var shirts = db.Shirts.ToArray();

            Console.BackgroundColor = ConsoleColor.White;
            Console.ForegroundColor = ConsoleColor.Black;
            Console.WriteLine("Color Ascending");
            Console.BackgroundColor = ConsoleColor.Black;
            Console.ForegroundColor = ConsoleColor.White;
            QuickSort.ColorAsc(shirts, 0, shirts.Length - 1);
            PrintAllItems(shirts);
            Console.BackgroundColor = ConsoleColor.White;
            Console.ForegroundColor = ConsoleColor.Black;
            Console.WriteLine("Color Descending");
            Console.BackgroundColor = ConsoleColor.Black;
            Console.ForegroundColor = ConsoleColor.White;
            QuickSort.ColorDesc(shirts, 0, shirts.Length - 1);
            PrintAllItems(shirts);
            Console.BackgroundColor = ConsoleColor.White;
            Console.ForegroundColor = ConsoleColor.Black;
            Console.WriteLine("Size Ascending");
            Console.BackgroundColor = ConsoleColor.Black;
            Console.ForegroundColor = ConsoleColor.White;
            QuickSort.SizeAsc(shirts, 0, shirts.Length - 1);
            PrintAllItems(shirts);
            Console.BackgroundColor = ConsoleColor.White;
            Console.ForegroundColor = ConsoleColor.Black;
            Console.WriteLine("Size Descending");
            Console.BackgroundColor = ConsoleColor.Black;
            Console.ForegroundColor = ConsoleColor.White;
            QuickSort.SizeDesc(shirts, 0, shirts.Length - 1);
            PrintAllItems(shirts);
            Console.BackgroundColor = ConsoleColor.White;
            Console.ForegroundColor = ConsoleColor.Black;
            Console.WriteLine("Fabric Ascending");
            Console.BackgroundColor = ConsoleColor.Black;
            Console.ForegroundColor = ConsoleColor.White;
            QuickSort.FabricAsc(shirts, 0, shirts.Length - 1);
            PrintAllItems(shirts);
            Console.BackgroundColor = ConsoleColor.White;
            Console.ForegroundColor = ConsoleColor.Black;
            Console.WriteLine("Fabric Descending");
            Console.BackgroundColor = ConsoleColor.Black;
            Console.ForegroundColor = ConsoleColor.White;
            QuickSort.FabricDesc(shirts, 0, shirts.Length - 1);
            PrintAllItems(shirts);



            //--------------------------------------------------BubbleSort-----------------------------------------------
            //Shirt[] arr = db.Shirts.ToArray();

            //[] arr1 = { new Int32(), new Int32(), new Int32(), new Int32(), new Int32(), new Int32() }; // πίνακας από αντικειμενα ιντ32


            var shirts1 = db.Shirts;

            Console.BackgroundColor = ConsoleColor.Gray;
            Console.ForegroundColor = ConsoleColor.Black;
            Console.WriteLine("BubbleSort SizeColorFabric Ascending");
            Console.BackgroundColor = ConsoleColor.Black;
            Console.ForegroundColor = ConsoleColor.White;
            BubbleSort.SizeColorFabricAsc2(shirts1);
            PrintAllItems(shirts1);


            Console.BackgroundColor = ConsoleColor.Gray;
            Console.ForegroundColor = ConsoleColor.Black;
            //  BubbleSort.SizeColorFabricAsc(shirts1);
            Console.WriteLine("BubbleSort SizeColorFabric Descending");
            Console.BackgroundColor = ConsoleColor.Black;
            Console.ForegroundColor = ConsoleColor.White;
            BubbleSort.SizeColorFabricDesc2(shirts1);
            // BubbleSort.SizeColorFabricDesc(shirts1);
            PrintAllItems(shirts1);



            Console.BackgroundColor = ConsoleColor.Gray;
            Console.ForegroundColor = ConsoleColor.Black;
            Console.WriteLine("BubbleSort Color Ascending");
            Console.BackgroundColor = ConsoleColor.Black;
            Console.ForegroundColor = ConsoleColor.White;
            BubbleSort.ColorAsc(shirts1);
            PrintAllItems(shirts1);

            Console.BackgroundColor = ConsoleColor.Gray;
            Console.ForegroundColor = ConsoleColor.Black;
            Console.WriteLine("BubbleSort Color Descending");
            Console.BackgroundColor = ConsoleColor.Black;
            Console.ForegroundColor = ConsoleColor.White;
            BubbleSort.ColorDesc(shirts1);
            PrintAllItems(shirts1);

            Console.BackgroundColor = ConsoleColor.Gray;
            Console.ForegroundColor = ConsoleColor.Black;
            Console.WriteLine("BubbleSort Size Ascending");
            Console.BackgroundColor = ConsoleColor.Black;
            Console.ForegroundColor = ConsoleColor.White;
            BubbleSort.SizeAsc(shirts1);
            PrintAllItems(shirts1);

            Console.BackgroundColor = ConsoleColor.Gray;
            Console.ForegroundColor = ConsoleColor.Black;
            Console.WriteLine("BubbleSort Size Descending");
            Console.BackgroundColor = ConsoleColor.Black;
            Console.ForegroundColor = ConsoleColor.White;
            BubbleSort.SizeDesc(shirts1);
            PrintAllItems(shirts1);

            Console.BackgroundColor = ConsoleColor.Gray;
            Console.ForegroundColor = ConsoleColor.Black;
            Console.WriteLine("BubbleSort Fabric Ascending");
            Console.BackgroundColor = ConsoleColor.Black;
            Console.ForegroundColor = ConsoleColor.White;
            BubbleSort.FabricAsc(shirts1);
            PrintAllItems(shirts1);

            Console.BackgroundColor = ConsoleColor.Gray;
            Console.ForegroundColor = ConsoleColor.Black;
            Console.WriteLine("BubbleSort Fabric Descending");
            Console.BackgroundColor = ConsoleColor.Black;
            Console.ForegroundColor = ConsoleColor.White;
            BubbleSort.FabricDesc(shirts1);
            PrintAllItems(shirts1);
        }
示例#10
0
        public Result SortAlgorithm([FromBody] Sort InputModel)
        {
            int[]  array = InputModel.array.ToArray();
            string text  = "Sorted";
            string text1 = "Mukesh Mahato";
            string text2 = "Quick Sort";
            string text3 = "Bubble sort";
            string text4 = "Insertion sort";
            string text5 = "Heap sort";
            int    len   = array.Length;
            check  c     = new check();

            c.IsSorted(array);
            c.IsSortedDescending(array);
            c.almostSort(array);
            c.sort(array);

            if (((c.IsSorted(array) || c.IsSortedDescending(array)) || (c.almostSort(array) || c.sort(array))) && (len > 30))
            {
                Stopwatch sw = Stopwatch.StartNew();
                QuickSort qs = new QuickSort();
                qs.Sort(array, 0, len - 1);
                sw.Stop();


                return(new Result()
                {
                    Created_by = text1,
                    Sorting_Algorithm = text2,
                    Status = text,
                    SortedArray = array,
                    ExecutionTime = sw.Elapsed.TotalMilliseconds
                });
            }

            else if (c.IsSorted(array) && c.almostSort(array) && c.sort(array))

            {
                if (len < 30)
                {
                    Stopwatch  sw = Stopwatch.StartNew();
                    BubbleSort bs = new BubbleSort();
                    bs.printArray(array);
                    sw.Stop();



                    return(new Result()
                    {
                        Created_by = text1,
                        Sorting_Algorithm = text3,
                        Status = text,
                        SortedArray = array,
                        ExecutionTime = sw.Elapsed.TotalMilliseconds
                    });
                }
                else
                {
                    Stopwatch     sw   = Stopwatch.StartNew();
                    InsertionSort Sort = new InsertionSort();
                    Sort.print(array);
                    sw.Stop();



                    return(new Result()
                    {
                        Created_by = text1,
                        Sorting_Algorithm = text4,
                        Status = text,
                        SortedArray = array,
                        ExecutionTime = sw.Elapsed.TotalMilliseconds
                    });
                }
            }

            else
            {
                Stopwatch sw   = Stopwatch.StartNew();
                HeapSort  Sort = new HeapSort();
                Sort.sort(array);
                sw.Stop();



                return(new Result()
                {
                    Created_by = text1,
                    Sorting_Algorithm = text5,
                    Status = text,
                    SortedArray = array,
                    ExecutionTime = sw.Elapsed.TotalMilliseconds
                });
            }
        }
示例#11
0
 public void BubbleSort_Sort_Success(int[] data)
 {
     BubbleSort.Sort(data);
     Assert.True(data.IsSorted());
 }
示例#12
0
        static void Main(string[] args)
        {
            #region Strategy

            //First Step
            Console.WriteLine("Initialize Strategy");

            long[] inputArray = new long[20];
            Random radom      = new Random();

            for (int strategy = 0; strategy < inputArray.Length; strategy++)
            {
                inputArray[strategy] = radom.Next(100);
            }

            foreach (long number in inputArray)
            {
                Console.WriteLine(number);
            }
            Console.ReadKey();

            //Second Step
            //Strategy 1
            var alg = new BubbleSort();
            alg.Sort(inputArray);
            Console.WriteLine("sort numbers");

            foreach (long number in inputArray)
            {
                Console.WriteLine(number);
            }

            Console.ReadKey();

            //Strategy 2
            var alg2 = new SelectionSort();
            alg2.Sort(inputArray);
            Console.WriteLine("sort numbers");
            foreach (long number in inputArray)
            {
                Console.WriteLine(number);
            }

            Console.ReadKey();

            //Apply Strategy Patterns
            Strategy.Context ctx = new Strategy.Context(new SelectionSort());
            ctx.ContextInterface(inputArray);
            Console.WriteLine("sort numbers");

            foreach (long number in inputArray)
            {
                Console.WriteLine(number);
            }

            Console.ReadKey();
            Console.WriteLine("Finalize Strategy" + Environment.NewLine);

            #endregion

            #region ChainOfResponsability

            Console.WriteLine("ChainOfResponsability Initialize");

            // First Step
            Validate validate = new Validate();
            Console.WriteLine(validate.ValidateUser("Test", "Test").ToString());

            ///Apply ChainOfResponsability pattern
            ChainOfResponsability.Form   valform   = new ChainOfResponsability.Form();
            ChainOfResponsability.Server valserver = new ChainOfResponsability.Server();
            BD valBD = new BD();

            valform.setSucessor(valserver);
            valserver.setSucessor(valBD);

            Console.WriteLine(valform.ValidateUser("Teste", "Teste").ToString());

            Console.WriteLine("ChainOfResponsability Finalize" + Environment.NewLine);

            #endregion

            #region Command

            Console.WriteLine("Command Initialize");

            //Configure Receiver
            Command.Server server = new Command.Server();

            //Create command and configure receiver.
            CommandAbstract cmd = new ServerCommand(server);

            //Configure invoker
            Command.Formulario form = new Command.Formulario();

            form.SetCommand(cmd);
            form.ClickValidate();
            Console.WriteLine("Command Finalize" + Environment.NewLine);
            Console.ReadLine();

            #endregion

            #region Iterator

            Console.WriteLine("Iterator Initialize");

            //Create concrete aggregate
            Team team = new Team();
            team[0] = "Luiz";
            team[0] = "Alex";
            team[0] = "Rodrigo";
            team[0] = "Renan";

            ConcreteIterator i = new ConcreteIterator(team);

            Console.WriteLine("Show team's members");

            Object item = i.First();

            while (item != null)
            {
                Console.WriteLine(item);
                item = i.Next();
            }

            Console.WriteLine("Iterator Finalize" + Environment.NewLine);
            Console.ReadLine();

            #endregion

            #region Mediator

            Console.WriteLine("Mediator Initialize");

            ConcreteMediator concreteMediator = new ConcreteMediator();
            Support          support          = new Support(concreteMediator);
            User             user             = new User(concreteMediator);

            concreteMediator.Suporte = support;
            concreteMediator.Usuario = user;

            support.Send("Hello user");
            user.Send("Hello support");

            Console.WriteLine("Mediator Finalize" + Environment.NewLine);
            Console.ReadLine();

            #endregion

            #region Memento

            Console.WriteLine("Memento Initialize");

            //Create originator
            Originator people = new Originator();
            people.State = "Bored";

            //Create caretaker
            Caretaker caretaker = new Caretaker();
            caretaker.Memento = people.CreateMemento();

            people.State = "Happy";
            Console.WriteLine("Actual State:" + people.State);

            people.setMemento(caretaker.Memento);
            Console.WriteLine("Restore State: " + people.State);

            Console.WriteLine("Memento Finalize" + Environment.NewLine);

            #endregion

            #region Observer

            Console.WriteLine("Observer Initialize");

            Balance balanco = new Balance();
            Sale    venda   = new Sale(balanco);

            balanco.Attach(venda);

            balanco.Iniciar();
            balanco.Notify();

            balanco.Finalizar();
            balanco.Notify();

            venda.Iniciar();

            //After remove observer
            balanco.Detach(venda);

            balanco.Iniciar();
            balanco.Notify();

            venda.Iniciar();

            Console.WriteLine("Observer Finalize" + Environment.NewLine);
            Console.ReadLine();

            #endregion

            #region State

            Console.WriteLine("State Initialize");

            Connection connection = new Connection(new ConnectionOpened());

            connection.Open();
            connection.Close();

            Console.WriteLine("State Finalize" + Environment.NewLine);
            Console.ReadLine();

            #endregion

            #region Template Method

            Console.WriteLine("Template Method Initialize");

            Correction proofCorrecion = new ProofCorrection();
            proofCorrecion.Process();

            Correction writingCorrection = new WritingCorrection();
            writingCorrection.Process();

            Console.WriteLine("Template Method Finalize" + Environment.NewLine);
            Console.ReadLine();

            #endregion

            #region Visitor

            Console.WriteLine("Visitor Initialize");

            //Config structure
            ObjectStructure objectStructure = new ObjectStructure();

            objectStructure.Attach(new ConcreteElementA());
            objectStructure.Attach(new ConcreteElementB());

            //Create Visitors
            ConcreteVisitor1 concreteVisitor1 = new ConcreteVisitor1();
            ConcreteVisitor2 concreteVisitor2 = new ConcreteVisitor2();

            objectStructure.Accept(concreteVisitor1);
            objectStructure.Accept(concreteVisitor2);

            Console.WriteLine("Visitor Finalize" + Environment.NewLine);
            Console.ReadLine();

            #endregion

            #region Interpreter

            Console.WriteLine("Interpreter Initialize");

            string roman = "MCMXXVIII";
            Interpreter.Context context = new Interpreter.Context(roman);

            List <Expression> tree = new List <Expression>();
            tree.Add(new ThousandExpression());
            tree.Add(new HundredExpression());
            tree.Add(new TenExpression());
            tree.Add(new OneExpression());

            foreach (Expression exp in tree)
            {
                exp.Interpret(context);
            }

            Console.WriteLine("{0} = {1}", roman, context.Output);

            Console.WriteLine("Interpreter Finalize" + Environment.NewLine);
            Console.ReadKey();

            #endregion
        }
 public void Init()
 {
     this.bubble     = new BubbleSort();
     this.collection = new List <int>();
 }
示例#14
0
        static void Main(string[] args)
        {
            Mine mine = new Mine();

            int[][] twoD = new int[2][];
            twoD[0] = new int[] { 0, 0 };
            twoD[1] = new int[] { 0, 1 };


            int[,] field = mine.Minesweeper(twoD, 3, 4);

            int mRow = field.GetUpperBound(0);
            int mCol = field.GetUpperBound(1);

            for (int r = 0; r <= mRow; r++)
            {
                for (int c = 0; c <= mCol; c++)
                {
                    Console.Write(field[r, c] + " ");
                }
                Console.WriteLine("");
            }

            int[]        bst          = { 2, 3, 4, 10, 40 };
            BinarySearch binarySearch = new BinarySearch();
            int          n            = bst.Length;
            int          x            = 10;

            Console.WriteLine("Recurcive: The index is " + binarySearch.BinarySearchRecursive(bst, 0, n - 1, x));
            Console.WriteLine("Itirative: The index is " + binarySearch.BinarySearchItirative(bst, x));


            var path = new List <int>();
            var Prev = new Dictionary <int, int>();

            Console.WriteLine(string.Join(", ", search.DFS(unDirectedgraph, 1)));
            Console.WriteLine(string.Join(", ", search.BFS(unDirectedgraph, 1, ref Prev, v => path.Add(v))));
            Console.WriteLine("Trace Path...");
            Console.WriteLine(string.Join(", ", path));
            foreach (var vertex in vertices)
            {
                Console.WriteLine("shortest path to {0,2}: {1}", vertex, string.Join(", ", search.ShortestPathFromPrev(Prev, 1, vertex)));
            }
            Console.WriteLine("Topological Sort....");
            Console.WriteLine(string.Join(", ", TopSort()));
            Console.WriteLine("Is 'create' anagram of 'eaterc'? : " + anagram.isAnagram("create", "eaterc"));

            void checkPalindrome(string str)
            {
                Palindrome p = new Palindrome();

                Console.WriteLine("Is this word a palindrome? " + str);
                Console.WriteLine(p.isPalidrome(str, false));
            };

            checkPalindrome("hello");
            checkPalindrome("motor");
            checkPalindrome("rotor");

            Misc misc = new Misc();

            int[] arr1 = { 5, 6, 1, 2, 3, 4 };
            int   n1   = arr1.Length;

            Console.WriteLine("The minimum element is " +
                              misc.FindMinInSortedRotated(arr1, 0, n1 - 1));

            int[] arr2 = { 1, 2, 3, 4 };
            int   n2   = arr2.Length;

            Console.WriteLine("The minimum element is " +
                              misc.FindMinInSortedRotated(arr2, 0, n2 - 1));

            int[] arr3 = { 1 };
            int   n3   = arr3.Length;

            Console.WriteLine("The minimum element is " +
                              misc.FindMinInSortedRotated(arr3, 0, n3 - 1));

            int[] arr4 = { 1, 2 };
            int   n4   = arr4.Length;

            Console.WriteLine("The minimum element is " +
                              misc.FindMinInSortedRotated(arr4, 0, n4 - 1));

            int[] arr5 = { 2, 1 };
            int   n5   = arr5.Length;

            Console.WriteLine("The minimum element is " +
                              misc.FindMinInSortedRotated(arr5, 0, n5 - 1));

            int[] arr6 = { 5, 6, 7, 1, 2, 3, 4 };
            int   n6   = arr6.Length;

            Console.WriteLine("The minimum element is " +
                              misc.FindMinInSortedRotated(arr6, 0, n1 - 1));

            int[] arr7 = { 1, 2, 3, 4, 5, 6, 7 };
            int   n7   = arr7.Length;

            Console.WriteLine("The minimum element is " +
                              misc.FindMinInSortedRotated(arr7, 0, n7 - 1));

            int[] arr8 = { 2, 3, 4, 5, 6, 7, 8, 1 };
            int   n8   = arr8.Length;

            Console.WriteLine("The minimum element is " +
                              misc.FindMinInSortedRotated(arr8, 0, n8 - 1));

            int[] arr9 = { 3, 4, 5, 1, 2 };
            int   n9   = arr9.Length;

            Console.WriteLine("The minimum element is " +
                              misc.FindMinInSortedRotated(arr9, 0, n9 - 1));

            int[]      arr   = { 64, 34, 25, 12, 22, 11, 90 };
            BubbleSort bSort = new BubbleSort();

            bSort.Sort(arr);
            Console.Write("arr = { 64, 34, 25, 12, 22, 11, 90 } => Sorted array = ");
            printArray(arr);

            int[]     ar = { 99, 44, 6, 2, 1, 5, 63, 87, 283, 4, 0 };
            QuickSort qs = new QuickSort();

            qs.Quick_Sort(ar);
            Console.Write("arr = { 99, 44, 6, 2, 1, 5, 63, 87, 283, 4, 0} => Insertion Sorted array = ");
            printArray(ar);

            int[]         arr_1 = { 64, 34, 25, 12, 22, 11, 90 };
            SelectionSort sSort = new SelectionSort();

            sSort.Sort(arr_1);
            Console.Write("arr_1 = { 64, 34, 25, 12, 22, 11, 90 } => Sorted array = ");
            printArray(arr_1);

            WordLadder wordLadder = new WordLadder();
            string     strpath    = "";
            int        i          = wordLadder.LadderLength("hit", "cog", ref strpath);

            Console.WriteLine(strpath);

            HammingWeight hw = new HammingWeight();

            int[] hw_1 = { 31, 51 };
            Console.WriteLine("Hamming Weight of hw_1 = {    31,51} = " + hw.GetHammingWeightbyPreprocessing(hw_1));

            Fibonacci fib = new Fibonacci();

            Console.WriteLine("6th Fibonacci number by rec is : " + fib.FibRecursive(6));
            Console.WriteLine("6th Fibonacci number by DP is : " + fib.FibDP(6));
            Console.WriteLine("6th Fibonacci number by Bottomup is : " + fib.FibBottomUp(6));

            Subsets subsets = new Subsets();

            int[] arrSS = new int[] { 2, 4, 6, 10 };
            Console.WriteLine("No. of subsets whose sum is 16 in { 2, 4, 6, 10 } : " + subsets.CountSubsetsDP(arrSS, 16));

            HasPairWithSum obj = new HasPairWithSum();

            Console.WriteLine("Does the array { 2, 4, 6, 10 } has a pair whose sum is 12: " + obj.isPairWithSumExists(arrSS, 12));

            MergeArrays ma = new MergeArrays();

            int[] arrSorted2 = new int[] { 0, 3, 4 };
            int[] arrSorted1 = new int[] { 2, 4, 6, 10 };

            Console.WriteLine("Merged Sorted array for the sorted arrays { 0, 3, 4} and { 2, 4, 6, 10 } : ");
            printArray(ma.MergeSortedArrays(arrSorted1, arrSorted2));

            MoveZeros mz = new MoveZeros();

            Console.WriteLine("Move Zeros from {0,0,1} ");
            int[] mzA = new int[] { 0, 0, 1 };
            mz.MoveZeroes(mzA);
            printArray(mzA);

            FirstRecurring fr = new FirstRecurring();

            int[] fra = new int[] { 2, 5, 1, 2, 3, 5, 1, 2, 4 };
            Console.WriteLine("First recurring element in  { 2, 5, 1, 2, 3, 5, 1, 2, 4 } is: " + fr.GetFirstRecurringElement <int>(fra));

            Islands il = new Islands();

            int[,] M = new int[, ] {
                { 1, 1, 0, 0, 0 },
                { 0, 1, 0, 0, 1 },
                { 1, 0, 0, 1, 1 },
                { 0, 0, 0, 0, 0 },
                { 1, 0, 1, 0, 1 }
            };
            Console.Write("Number of islands is: " +
                          il.countIslands(M));

            LongestPalindromicSubstring lss = new LongestPalindromicSubstring();

            Console.Write("LongestPalindrome in 'babad' : " + lss.LongestPalindrome("cbbd"));


            BinaryTree tree = new BinaryTree();

            tree.root            = new TreeNode(1);
            tree.root.left       = new TreeNode(2);
            tree.root.right      = new TreeNode(3);
            tree.root.left.left  = new TreeNode(4);
            tree.root.left.right = new TreeNode(5);
            Console.WriteLine("");
            Traversals trav = new Traversals();

            trav.printInorder(tree.root);
            Console.WriteLine("");
            trav.printPreorder(tree.root);
            Console.WriteLine("");
            trav.printPostOrder(tree.root);
            Console.WriteLine("");

            Console.Write("The height of the tree is : " + trav.GetTreeHeight(tree.root));
            Console.WriteLine("Level Order:");
            trav.LevelOrderTraversal(tree.root);
        }
示例#15
0
        private async void Button3_Click(object sender, EventArgs e)
        {
            AlgorithmsBase <int> algorithmsBase = null;
            var Items     = new List <int>();
            var timeSpan  = new List <TimeSpan>();
            var swapCount = new List <int>();

            richTextBoxParser(Items);

            #region Методы для вычисления сортировок.

            algorithmsBase = new BubbleSort <int>();
            await Task.Run(() => AnalysisAlgorithm(algorithmsBase, Items, timeSpan, swapCount));

            await Task.Run(() => richTextBox2.Invoke((Action) delegate
            {
                richTextBoxFill(Constants.BubbleSort, timeSpan[0], swapCount[0]);
            }
                                                     ));

            algorithmsBase = new CoctailSort <int>();
            await Task.Run(() => AnalysisAlgorithm(algorithmsBase, Items, timeSpan, swapCount));

            await Task.Run(() => richTextBox2.Invoke((Action) delegate
            {
                richTextBoxFill(Constants.CoctailSort, timeSpan[1], swapCount[1]);
            }
                                                     ));

            algorithmsBase = new InsertSort <int>();
            await Task.Run(() => AnalysisAlgorithm(algorithmsBase, Items, timeSpan, swapCount));

            await Task.Run(() => richTextBox2.Invoke((Action) delegate
            {
                richTextBoxFill(Constants.InsertionSort, timeSpan[2], swapCount[2]);
            }
                                                     ));

            algorithmsBase = new ShellSort <int>();
            await Task.Run(() => AnalysisAlgorithm(algorithmsBase, Items, timeSpan, swapCount));

            await Task.Run(() => richTextBox2.Invoke((Action) delegate
            {
                richTextBoxFill(Constants.ShellSort, timeSpan[3], swapCount[3]);
            }
                                                     ));

            algorithmsBase = new HeapSort <int>();
            await Task.Run(() => AnalysisAlgorithm(algorithmsBase, Items, timeSpan, swapCount));

            await Task.Run(() => richTextBox2.Invoke((Action) delegate
            {
                richTextBoxFill(Constants.HeapSort, timeSpan[4], swapCount[4]);
            }
                                                     ));

            algorithmsBase = new TreeSort <int>();
            await Task.Run(() => AnalysisAlgorithm(algorithmsBase, Items, timeSpan, swapCount));

            await Task.Run(() => richTextBox2.Invoke((Action) delegate
            {
                richTextBoxFill(Constants.TreeSort, timeSpan[5], swapCount[5]);
            }
                                                     ));

            algorithmsBase = new SelectionSort <int>();
            await Task.Run(() => AnalysisAlgorithm(algorithmsBase, Items, timeSpan, swapCount));

            await Task.Run(() => richTextBox2.Invoke((Action) delegate
            {
                richTextBoxFill(Constants.SelectionSort, timeSpan[6], swapCount[6]);
            }
                                                     ));

            algorithmsBase = new GnomeSort <int>();
            await Task.Run(() => AnalysisAlgorithm(algorithmsBase, Items, timeSpan, swapCount));

            await Task.Run(() => richTextBox2.Invoke((Action) delegate
            {
                richTextBoxFill(Constants.GnomeSort, timeSpan[7], swapCount[7]);
            }
                                                     ));

            algorithmsBase = new MergeSort <int>();
            await Task.Run(() => AnalysisAlgorithm(algorithmsBase, Items, timeSpan, swapCount));

            await Task.Run(() => richTextBox2.Invoke((Action) delegate
            {
                richTextBoxFill(Constants.MergeSort, timeSpan[8], swapCount[8]);
            }
                                                     ));

            algorithmsBase = new QuickSort <int>();
            await Task.Run(() => AnalysisAlgorithm(algorithmsBase, Items, timeSpan, swapCount));

            await Task.Run(() => richTextBox2.Invoke((Action) delegate
            {
                richTextBoxFill(Constants.QuickSort, timeSpan[9], swapCount[9]);
            }
                                                     ));

            #endregion

            button3.Enabled = false;

            string[] seriesArray = new string[10];
            int[]    pointsArray = new int[10];

            chart1.Series.Clear();
            var countSeries = 0;
            checkBoxCheckedAll(ref countSeries, seriesArray, pointsArray, swapCount);
            chartDefaultSettings(countSeries, pointsArray.Max());

            for (int i = 0; i < seriesArray.Length; i++)
            {
                if (seriesArray[i] != null)
                {
                    Series series = chart1.Series.Add(seriesArray[i]);
                    series.Points.Add(pointsArray[i]);
                }
            }
        }
 public void IComparerArgumentIsNull_Should_ThroughArgumentNullExceptionTest()
 {
     int[][] arrayToSort = null;
     Assert.Catch(typeof(ArgumentNullException), () => BubbleSort.Sort(arrayToSort, new SortBySumAscending()), "required type of exception is not thrown");
 }
示例#17
0
 public void SortSingleElementSortedArray()
 {
     int[] input = { 1 };
     Assert.Equal(BubbleSort.SortIntegers(input), input);
 }
示例#18
0
 public void SortThreeElementUnsortedArray()
 {
     int[] input          = { 3, 2, 1 };
     int[] expectedOutput = { 1, 2, 3 };
     Assert.Equal(expectedOutput, BubbleSort.SortIntegers(input));
 }
示例#19
0
 public void SortFourElementSortedArray()
 {
     int[] input = { 1, 2, 3, 4 };
     Assert.Equal(input, BubbleSort.SortIntegers(input));
 }
示例#20
0
 private void pb_Search_Click(object sender, EventArgs e)
 {
     if (tb_Search.Text.ToString() == "스택(Stack)")
     {
         stack             = new Stack();
         stack.FormClosed += Stack_FormClosed;
         stack.Show();
         this.Close();
     }
     if (tb_Search.Text.ToString() == "연결리스트(LinkedList)")
     {
         ll             = new LinkedList();
         ll.FormClosed += Ll_FormClosed;
         ll.Show();
         this.Close();
     }
     if (tb_Search.Text.ToString() == "삽입정렬(InsertSort)")
     {
         Is             = new InsertSort();
         Is.FormClosed += Is_FormClosed;
         Is.Show();
         this.Close();
     }
     if (tb_Search.Text.ToString() == "선택정렬(SelectionSort)")
     {
         ss             = new SelectionSort();
         ss.FormClosed += Ss_FormClosed;
         ss.Show();
         this.Close();
     }
     if (tb_Search.Text.ToString() == "이진탐색트리(BinarySearchTree)")
     {
         bst             = new BinarySearchTree();
         bst.FormClosed += Bst_FormClosed;
         bst.Show();
         this.Close();
     }
     if (tb_Search.Text.ToString() == "큐(Queue)")
     {
         q             = new QUeue();
         q.FormClosed += Q_FormClosed;
         q.Show();
         this.Close();
     }
     if (tb_Search.Text.ToString() == "쉘정렬(ShellSort)")
     {
         shellSort             = new ShellSort();
         shellSort.FormClosed += ShellSort_FormClosed;
         shellSort.Show();
         this.Close();
     }
     if (tb_Search.Text.ToString() == "깊이우선탐색(Depth-first search)")
     {
         dfs             = new DepthFirstSearch();
         dfs.FormClosed += Dfs_FormClosed;
         dfs.Show();
         this.Close();
     }
     if (tb_Search.Text.ToString() == "너비우선탐색(Breadth-first search)")
     {
         bfs             = new BreadthFirstSearch();
         bfs.FormClosed += Bfs_FormClosed;
         bfs.Show();
         this.Close();
     }
     if (tb_Search.Text.ToString() == "버블정렬(BubbleSort)")
     {
         bs             = new BubbleSort();
         bs.FormClosed += Bs_FormClosed;
         bs.Show();
         this.Close();
     }
     if (tb_Search.Text.ToString() == "퀵정렬(QuickSort)")
     {
         qs             = new QuickSort();
         qs.FormClosed += Qs_FormClosed;
         qs.Show();
         this.Close();
     }
     if (tb_Search.Text.ToString() == "힙정렬(HeapSort)")
     {
         hs             = new HeapSort();
         hs.FormClosed += Hs_FormClosed;
         hs.Show();
         this.Close();
     }
     if (tb_Search.Text.ToString() == "기수정렬(RadixSort)")
     {
         rs             = new RadixSort();
         rs.FormClosed += Rs_FormClosed;
         rs.Show();
         this.Close();
     }
     if (tb_Search.Text.ToString() == "버킷정렬(BucketSort)")
     {
         bucketsort             = new BucketSort();
         bucketsort.FormClosed += Bucketsort_FormClosed;
         bucketsort.Show();
         this.Close();
     }
     if (tb_Search.Text.ToString() == "다익스트라알고리즘(Dijkstra algorithm)")
     {
         dijkstra             = new Dijkstra();
         dijkstra.FormClosed += Dijkstra_FormClosed;
         dijkstra.Show();
         this.Close();
     }
     if (tb_Search.Text.ToString() == "프림알고리즘(Prim's algorithm)")
     {
         prim             = new Prim();
         prim.FormClosed += Prim_FormClosed;
         prim.Show();
         this.Close();
     }
     if (tb_Search.Text.ToString() == "머지정렬(MergeSort)")
     {
         mergesort             = new MergeSort();
         mergesort.FormClosed += Mergesort_FormClosed;
         mergesort.Show();
         this.Close();
     }
     if (tb_Search.Text.ToString() == "카운팅정렬(CountingSort)")
     {
         cs             = new CountingSort();
         cs.FormClosed += Cs_FormClosed;
         cs.Show();
         this.Close();
     }
 }
 public void TestSetup()
 {
     Sorter = new BubbleSort();
     ValuesToSort = new List<int> { 1, 5, 3, 9, -11, 5 };
 }
示例#22
0
 public void TestInit() {
     _sort = new BubbleSort();
 }
示例#23
0
        public void TestBubbleSort(int[] input)
        {
            BubbleSort.Perform(input);

            AssertHelper.IsSorted(input);
        }
示例#24
0
 /// <summary>
 /// 初始化签名生成器
 /// </summary>
 public SignBuilder() {
     _params = new Str();
     _data = new List<string>();
     _sort = new BubbleSort();
     _key = string.Empty;
 }
示例#25
0
 public void SetUp()
 {
     _sort = new BubbleSort();
     _filler = new EnumerationHoleFiller();
     _finder = new EnumerationHoleFinder();
 }
示例#26
0
        private void BtnOrdenar_Click(object sender, EventArgs e)
        {
            List <Candidato> candidatoList = null;

            try
            {
                candidatoList = (List <Candidato>)candidatoBindingSource.DataSource;
            }
            catch (Exception) { }

            if (candidatoList == null)
            {
                MessageBox.Show("Carregue os dados antes de ordenar.");
                return;
            }

            List <Candidato> resultadoOrdenado = new List <Candidato>();

            // Bubble Sort
            if (rbBubbleSort.Checked && rbNome.Checked)
            {
                resultadoOrdenado.Clear();
                BubbleSort bubbleSort = new BubbleSort(candidatoList, TIPO.NOME);
                resultadoOrdenado = bubbleSort.Sort();
                lblTempo.Text     = Convert.ToString(bubbleSort.StopWatch.Elapsed);
            }

            if (rbBubbleSort.Checked && rbInscricao.Checked)
            {
                resultadoOrdenado.Clear();
                BubbleSort bubbleSort = new BubbleSort(candidatoList, TIPO.MATRICULA);
                resultadoOrdenado = bubbleSort.Sort();
                lblTempo.Text     = Convert.ToString(bubbleSort.StopWatch.Elapsed);
            }

            if (rbBubbleSort.Checked && rbNota.Checked)
            {
                resultadoOrdenado.Clear();
                BubbleSort bubbleSort = new BubbleSort(candidatoList, TIPO.NOTA);
                resultadoOrdenado = bubbleSort.Sort();
                lblTempo.Text     = Convert.ToString(bubbleSort.StopWatch.Elapsed);
            }

            // Selection Sort
            if (rbSelectionSort.Checked && rbNome.Checked)
            {
                resultadoOrdenado.Clear();
                SelectionSort selectionSort = new SelectionSort(candidatoList, TIPO.NOME);
                resultadoOrdenado = selectionSort.sort();
                lblTempo.Text     = Convert.ToString(selectionSort.StopWatch.Elapsed);
            }

            if (rbSelectionSort.Checked && rbInscricao.Checked)
            {
                resultadoOrdenado.Clear();
                SelectionSort selectionSort = new SelectionSort(candidatoList, TIPO.MATRICULA);
                resultadoOrdenado = selectionSort.sort();
                lblTempo.Text     = Convert.ToString(selectionSort.StopWatch.Elapsed);
            }

            if (rbSelectionSort.Checked && rbNota.Checked)
            {
                resultadoOrdenado.Clear();
                SelectionSort selectionSort = new SelectionSort(candidatoList, TIPO.NOTA);
                resultadoOrdenado = selectionSort.sort();
                lblTempo.Text     = Convert.ToString(selectionSort.StopWatch.Elapsed);
            }

            // Insertion Sort
            if (rbInsertionSort.Checked && rbNome.Checked)
            {
                resultadoOrdenado.Clear();
                InsertionSort insertionSort = new InsertionSort(candidatoList, TIPO.NOME);
                resultadoOrdenado = insertionSort.sort();
                lblTempo.Text     = Convert.ToString(insertionSort.StopWatch.Elapsed);
            }

            if (rbInsertionSort.Checked && rbInscricao.Checked)
            {
                resultadoOrdenado.Clear();
                InsertionSort insertionSort = new InsertionSort(candidatoList, TIPO.MATRICULA);
                resultadoOrdenado = insertionSort.sort();
                lblTempo.Text     = Convert.ToString(insertionSort.StopWatch.Elapsed);
            }

            if (rbInsertionSort.Checked && rbNota.Checked)
            {
                resultadoOrdenado.Clear();
                InsertionSort insertionSort = new InsertionSort(candidatoList, TIPO.NOTA);
                resultadoOrdenado = insertionSort.sort();
                lblTempo.Text     = Convert.ToString(insertionSort.StopWatch.Elapsed);
            }

            // Merge Sort
            if (rbMergeSort.Checked && rbNome.Checked)
            {
                resultadoOrdenado.Clear();
                MergeSort mergeSort = new MergeSort(TIPO.NOME);
                resultadoOrdenado = mergeSort.sort(candidatoList);
                lblTempo.Text     = Convert.ToString(mergeSort.StopWatch.Elapsed);
            }

            if (rbMergeSort.Checked && rbInscricao.Checked)
            {
                resultadoOrdenado.Clear();
                MergeSort mergeSort = new MergeSort(TIPO.MATRICULA);
                resultadoOrdenado = mergeSort.sort(candidatoList);
                lblTempo.Text     = Convert.ToString(mergeSort.StopWatch.Elapsed);
            }

            if (rbMergeSort.Checked && rbNota.Checked)
            {
                resultadoOrdenado.Clear();
                MergeSort mergeSort = new MergeSort(TIPO.NOTA);
                resultadoOrdenado = mergeSort.sort(candidatoList);
                lblTempo.Text     = Convert.ToString(mergeSort.StopWatch.Elapsed);
            }

            // Quick Sort
            if (rbQuickSort.Checked && rbNome.Checked)
            {
                resultadoOrdenado.Clear();
                QuickSort quickSort = new QuickSort(TIPO.NOME);
                resultadoOrdenado = quickSort.sort(candidatoList);
                lblTempo.Text     = Convert.ToString(quickSort.StopWatch.Elapsed);
            }

            if (rbQuickSort.Checked && rbInscricao.Checked)
            {
                resultadoOrdenado.Clear();
                QuickSort quickSort = new QuickSort(TIPO.MATRICULA);
                resultadoOrdenado = quickSort.sort(candidatoList);
                lblTempo.Text     = Convert.ToString(quickSort.StopWatch.Elapsed);
            }

            if (rbQuickSort.Checked && rbNota.Checked)
            {
                resultadoOrdenado.Clear();
                QuickSort quickSort = new QuickSort(TIPO.NOTA);
                resultadoOrdenado = quickSort.sort(candidatoList);
                lblTempo.Text     = Convert.ToString(quickSort.StopWatch.Elapsed);
            }

            candidatoBindingSource.Clear();
            candidatoBindingSource.DataSource = resultadoOrdenado;
            lblTotal.Text = Convert.ToString(resultadoOrdenado.Count);
        }
示例#27
0
 public SortingAlghorithsTest()
 {
     bubbleSort = new BubbleSort();
 }
示例#28
0
 public void SetUp()
 {
     _sort = new BubbleSort();
 }
示例#29
0
        static void Main(string[] args)
        {
            ClothesPlannerStrategy shirtStrategy = new ClothesPlannerStrategy();

            shirtStrategy.ExecuteStrategy(new Shirt());

            SynthticData db       = new SynthticData();
            var          newLista = new List <Shirt>(db.Shirts);

            //BubbleSort
            Console.WriteLine("Sorting By Size with Bubble Method");
            BubbleSort.SortShirtsSize(newLista);
            foreach (var item in newLista)
            {
                item.Output();
            }

            Console.WriteLine("Sorting By SizeDesc with Bubble Method");
            BubbleSort.SortShirtsSizeDesc(newLista);
            foreach (var item in newLista)
            {
                item.Output();
            }

            Console.WriteLine("Sorting By FabricDesc with Bubble Method");
            BubbleSort.SortShirtsFabricDesc(newLista);
            foreach (var item in newLista)
            {
                item.Output();
            }

            Console.WriteLine("Sorting By ColorDesc with Bubble Method");
            BubbleSort.SortShirtsColourDesc(newLista);
            foreach (var item in newLista)
            {
                item.Output();
            }

            //QuickSort
            Console.WriteLine("Sorting By Fabric with QuickSort Method");
            QuickSort.SortShirtsFabric(newLista);
            foreach (var item in newLista)
            {
                item.Output();
            }

            //BucketSort
            Console.WriteLine("Sorting By Color with Bucket Method");
            var sortedListBucketColor = BucketSort.SortShirtsColor(newLista);

            foreach (var item in sortedListBucketColor)
            {
                item.Output();
            }

            // Asc with Bubbles Method 3color-size-fabric
            Console.WriteLine("Sorting By 3Asc with Bubble Method");
            BubbleSort.SortShirts3Asc(newLista);
            foreach (var item in newLista)
            {
                item.Output();
            }

            // Desc with Bubbles Method 3color-size-fabric
            Console.WriteLine("Sorting By 3Desc with Bubble Method");
            BubbleSort.SortShirts3Desc(newLista);
            foreach (var item in newLista)
            {
                item.Output();
            }

            try
            {
                Console.WriteLine("If you want to pay with Credit Card please write 1");
                Console.WriteLine("If you want to pay with  Bank Transfer please write 2");
                Console.WriteLine("If you want to pay with Cash please write 3");
                int num = Convert.ToInt32(Console.ReadLine());
                shirtStrategy.PayMethods(num);
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
            }
            finally { };
        }
示例#30
0
        static void Main(string[] args)
        {
            int[] arr = new int[10000];
            Random rnd = new Random();
            for (int i = 0; i < arr.Length; i++)
            {
                arr[i] = rnd.Next(10000);
            }
            ISort<int> s = new BubbleSort<int>();
            DateTime dt = DateTime.Now;
            arr = s.Sorting(arr);
            Console.WriteLine("Time for BubbleSort is {0}.", DateTime.Now - dt);

            for (int i = 0; i < arr.Length; i++)
            {
                arr[i] = rnd.Next(10000);
            }
            dt = DateTime.Now;
            s = new CocktailSort<int>();
            arr = s.Sorting(arr);
            Console.WriteLine("Time for CocktailSort is {0}.", DateTime.Now - dt);

            for (int i = 0; i < arr.Length; i++)
            {
                arr[i] = rnd.Next(10000);
            }
            dt = DateTime.Now;
            s = new EvenOddSort<int>();
            arr = s.Sorting(arr);
            Console.WriteLine("Time for EvenOddSort is {0}.", DateTime.Now - dt);

            for (int i = 0; i < arr.Length; i++)
            {
                arr[i] = rnd.Next(10000);
            }
            dt = DateTime.Now;
            s = new CombSort<int>();
            arr = s.Sorting(arr);
            Console.WriteLine("Time for CombSort is {0}.", DateTime.Now - dt);

            for (int i = 0; i < arr.Length; i++)
            {
                arr[i] = rnd.Next(10000);
            }
            dt = DateTime.Now;
            s = new GnomeSort<int>();
            arr = s.Sorting(arr);
            Console.WriteLine("Time for GnomeSort is {0}.", DateTime.Now - dt);

            arr = new int[10000];
            for (int i = 0; i < arr.Length; i++)
            {
                arr[i] = rnd.Next(10000);
            }
            dt = DateTime.Now;
            s = new InsertionSort<int>();
            arr = s.Sorting(arr);
            Console.WriteLine("Time for InsertionSort is {0}.", DateTime.Now - dt);

            for (int i = 0; i < arr.Length; i++)
            {
                arr[i] = rnd.Next(10000);
            }
            dt = DateTime.Now;
            s = new BinaryInsertionSort<int>();
            arr = s.Sorting(arr);
            Console.WriteLine("Time for BinaryInsertionSort is {0}.", DateTime.Now - dt);

            for (int i = 0; i < arr.Length; i++)
            {
                arr[i] = rnd.Next(10000);
            }
            dt = DateTime.Now;
            s = new ShellSort<int>();
            arr = s.Sorting(arr);
            Console.WriteLine("Time for ShellSort is {0}.", DateTime.Now - dt);

            arr = new int[1000000];
            for (int i = 0; i < arr.Length; i++)
            {
                arr[i] = rnd.Next(1000000);
            }
            for (int i = 0; i < arr.Length; i++)
            {
                arr[i] = rnd.Next(10000);
            }
            dt = DateTime.Now;
            s = new HeapSort<int>();
            arr = s.Sorting(arr);
            Console.WriteLine("Time for HeapSort is {0}.", DateTime.Now - dt);
            int ddd = 0;
            for (int i = 0; i < arr.Length - 2; i++)
            {
                //Console.Write(arr[i] + " ");
                if (arr[i] > arr[i + 1]) //Console.WriteLine("Fatal ERROR!!!");
                    ddd++;
            }
            Console.WriteLine("Error count: {0}", ddd);

            dt = DateTime.Now;
            s = new MergeSort<int>();
            arr = s.Sorting(arr);
            Console.WriteLine("Time for MergeSort is {0}.", DateTime.Now - dt);

            //StreamWriter sw = new StreamWriter("C:/Users/suvorovi/1.txt");
            for (int i = 0; i < arr.Length; i++)
            {
                arr[i] = rnd.Next(1000000);
                //sw.Write(arr[i] + " ");
            }
            //sw.WriteLine("");
            dt = DateTime.Now;
            s = new QuickSort<int>();
            arr = s.Sorting(arr);
            Console.WriteLine("Time for QuickSort is {0}.", DateTime.Now - dt);
            for (int i = 0; i < arr.Length; i++)
            {
                arr[i] = rnd.Next(1000000);
                //sw.Write(arr[i] + " ");
            }
            //sw.WriteLine("");
            dt = DateTime.Now;
            s = new TimSort<int>();
            arr = s.Sorting(arr);
            Console.WriteLine("Time for TimSort is {0}.", DateTime.Now - dt);
            ddd = 0;
            for (int i = 0; i < arr.Length - 2; i++)
            {
                //Console.Write(arr[i] + " ");
                if (arr[i] > arr[i + 1]) //Console.WriteLine("Fatal ERROR!!!");
                    ddd++;
            }
            Console.WriteLine("Error count: {0}", ddd);
            Console.ReadLine();
            //sw.Close();
        }
示例#31
0
 static void BubbleSort(int[] values)
 {
     BubbleSort <int> bsort = new BubbleSort <int>();
     var sorted             = bsort.Sort(values);
 }