예제 #1
0
        public void CanDoSelectionSort(int[] input, int[] expected)
        {
            var sut = new SelectionSort();
            var actual = sut.Sort(input);

            Assert.Equal(expected, actual);
        }
예제 #2
0
        public void SelectionSortTest()
        {
            var sorter = new SelectionSort<int>();
            sorter.Sort(shuffledList);
            var temp = shuffledList.ToArray();
            Array.Sort(temp);
            CollectionAssert.AreEqual(temp, shuffledList);

            //one element
            var collection = new[] { 0 };
            sorter.Sort(collection);
            temp = collection.ToArray();
            Array.Sort(temp);
            CollectionAssert.AreEqual(temp, collection);

            //zero elements
            collection = new int[0];
            sorter.Sort(collection);
            temp = collection.ToArray();
            Array.Sort(temp);
            CollectionAssert.AreEqual(temp, collection);

            //null elements
            collection = null;
            sorter.Sort(collection);
            CollectionAssert.AreEqual(null, collection);
        }
예제 #3
0
        public void CanSortUsingMergeSort(int[] input, int[] expected)
        {
            var sectionSort = new SelectionSort();
            var sut = new MergeSort(sectionSort);

            var actual = sut.Sort(input);

            Assert.Equal(expected, actual);
        }
예제 #4
0
        public static Sort GetSort()
        {
            // make the chain of invocations
            var selectSort = new SelectionSort();
            var quickSort = new QuickSort();
            selectSort.NextInChain = quickSort;

            return selectSort;
        }
예제 #5
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);
        }
예제 #6
0
        public void IsSortedTest()
        {
            Random rnd = new Random();

            const int n = 1000;
            int[] array = new List<int>(Enumerable.Range(1,n).Select(v => rnd.Next())).ToArray();

            SelectionSort<int> sort = new SelectionSort<int>();

            array = sort.Sort(array);

            Assert.IsTrue(TestHelpers<int>.IsSorted(array));
        }
        static void Main()
        {
            var dimensions = new[] {100, 1000, 5000, 10000, 50000, 100000};

            foreach (var dimension in dimensions)
            {
                Console.WriteLine("Calculating {0} array size", dimension);
                Console.WriteLine("------------");

                var randomQuickSort = new RandomQuickSort(dimension);
                var radixSort = new RadixSort(dimension);
                var selectionSort = new SelectionSort(dimension);

                Console.WriteLine("Randomized QuickSort: {0}", SortingBenchmark.Measure(randomQuickSort.Sort));
                Console.WriteLine("Radix Sort: {0}", SortingBenchmark.Measure(radixSort.Sort));
                Console.WriteLine("Selection Sort: {0}", SortingBenchmark.Measure(selectionSort.Sort));
            }
        }
예제 #8
0
        static void Main(string[] args)
        {
            Stopwatch watch = new Stopwatch();

            List<char> mainList = new List<char>();
            Random x = new Random();
            for (int i = 0; i < 100000; i++)
            {
                mainList.Add((char)x.Next(97,122));
            }

            Console.WriteLine("Selection Sort: ");
            SelectionSort s = new SelectionSort();
            TimeSpan selectionTime;
            watch.Start();
            List<char> selectionList = s.Sort<List<char>, char>(mainList, Comparer<char>.Default);
            watch.Stop();
            selectionTime = watch.Elapsed;
            string selectionElapsedTime = String.Format("{0:00}:{1:00}:{2:00}.{3:00}", selectionTime.Hours, selectionTime.Minutes, selectionTime.Seconds, selectionTime.Milliseconds / 10);
            Console.WriteLine("\nTime " + selectionElapsedTime + "\n");
            watch.Reset();

            Console.WriteLine("Gnome Sort: ");
            GnomeSort g = new GnomeSort();
            TimeSpan gnomeTime;
            watch.Start();
            List<char> gnomeList = s.Sort<List<char>, char>(mainList, Comparer<char>.Default);
            watch.Stop();
            gnomeTime = watch.Elapsed;
            string gnomeElapsedTime = String.Format("{0:00}:{1:00}:{2:00}.{3:00}", gnomeTime.Hours, gnomeTime.Minutes, gnomeTime.Seconds, gnomeTime.Milliseconds / 10);
            Console.WriteLine("\nTime " + gnomeElapsedTime + "\n");
            watch.Reset();

            Console.WriteLine("Comb Sort: ");
            SelectionSort c = new SelectionSort();
            TimeSpan combTime;
            watch.Start();
            List<char> combList = s.Sort<List<char>, char>(mainList, Comparer<char>.Default);
            watch.Stop();
            combTime = watch.Elapsed;
            string combElapsedTime = String.Format("{0:00}:{1:00}:{2:00}.{3:00}", combTime.Hours, combTime.Minutes, combTime.Seconds, combTime.Milliseconds / 10);
            Console.WriteLine("\nTime " + combElapsedTime + "\n");
            watch.Reset();
        }
예제 #9
0
 public void SortWithComparerTest_DESCOrder_NullArray()
 {
     SelectionSort.Sort(null, Point.X_ORDER, SortOrder.DESC);
 }
예제 #10
0
 public void SortWithComparerTest_NullArray()
 {
     SelectionSort.Sort(null, Point.X_ORDER);
 }
예제 #11
0
 public void SortTest_DESCOrder_NullArray()
 {
     SelectionSort.Sort(null, SortOrder.DESC);
 }
예제 #12
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);
        }
예제 #13
0
        public void TestSelectionSort(int[] input)
        {
            SelectionSort.Perform(input);

            AssertHelper.IsSorted(input);
        }
예제 #14
0
        static void Main(string[] args)
        {
            int[]      arr_bs = { 7, 26, 53, 22, 32, 28, 38, 23, 24, 54, 27, 78, 33 };
            BubbleSort bs     = new BubbleSort();

            Console.WriteLine("冒泡排序:");
            bs.MyBulleSort(arr_bs);

            /*result
             *  7 26 22 32 28 38 23 24 53 27 54 33 78
             *  7 22 26 28 32 23 24 38 27 53 33 54 78
             *  7 22 26 28 23 24 32 27 38 33 53 54 78
             *  7 22 26 23 24 28 27 32 33 38 53 54 78
             *  7 22 23 24 26 27 28 32 33 38 53 54 78
             *  7 22 23 24 26 27 28 32 33 38 53 54 78
             *  7 22 23 24 26 27 28 32 33 38 53 54 78
             *  7 22 23 24 26 27 28 32 33 38 53 54 78
             *  7 22 23 24 26 27 28 32 33 38 53 54 78
             *  7 22 23 24 26 27 28 32 33 38 53 54 78
             *  7 22 23 24 26 27 28 32 33 38 53 54 78
             *  7 22 23 24 26 27 28 32 33 38 53 54 78
             *  程序的运行时间:0.0242318 秒
             */

            int[]     arr_qs = { 7, 26, 53, 22, 32, 28, 38, 23, 24, 54, 27, 78, 33 };
            QuickSort qs     = new QuickSort();

            Console.WriteLine("快速排序:");
            qs.MyQuickSort(arr_qs, 0, arr_qs.Length - 1);

            /*result
             *  7 26 53 22 32 28 38 23 24 54 27 78 33
             *  7 24 23 22 26 28 38 32 53 54 27 78 33
             *  7 22 23 24 26 28 38 32 53 54 27 78 33
             *  7 22 23 24 26 28 38 32 53 54 27 78 33
             *  7 22 23 24 26 27 28 32 53 54 38 78 33
             *  7 22 23 24 26 27 28 32 53 54 38 78 33
             *  7 22 23 24 26 27 28 32 33 38 53 78 54
             *  7 22 23 24 26 27 28 32 33 38 53 78 54
             *  7 22 23 24 26 27 28 32 33 38 53 54 78
             */

            int[]         arr_ins = { 7, 26, 53, 22, 32, 28, 38, 23, 24, 54, 27, 78, 33 };
            InsertionSort ins     = new InsertionSort();

            Console.WriteLine("插入排序:");
            ins.MyInsertionSort(arr_ins);

            /*result
             *  7 26 53 22 32 28 38 23 24 54 27 78 33
             *  7 26 53 22 32 28 38 23 24 54 27 78 33
             *  7 22 26 53 32 28 38 23 24 54 27 78 33
             *  7 22 26 32 53 28 38 23 24 54 27 78 33
             *  7 22 26 28 32 53 38 23 24 54 27 78 33
             *  7 22 26 28 32 38 53 23 24 54 27 78 33
             *  7 22 23 26 28 32 38 53 24 54 27 78 33
             *  7 22 23 24 26 28 32 38 53 54 27 78 33
             *  7 22 23 24 26 28 32 38 53 54 27 78 33
             *  7 22 23 24 26 27 28 32 38 53 54 78 33
             *  7 22 23 24 26 27 28 32 38 53 54 78 33
             *  7 22 23 24 26 27 28 32 33 38 53 54 78
             */

            int[]     arr_shs = { 7, 26, 53, 22, 32, 28, 38, 23, 24, 54, 27, 78, 33 };
            ShellSort shs     = new ShellSort();

            Console.WriteLine("希尔排序:");
            shs.MyShellSort(arr_shs);

            /*result
             *  gap=13
             *  本轮结果:
             *  7 26 53 22 32 28 38 23 24 54 27 78 33
             *  gap=4
             *  7 26 53 22 32 28 38 23 24 54 27 78 33
             *  7 26 53 22 32 28 38 23 24 54 27 78 33
             *  7 26 38 22 32 28 53 23 24 54 27 78 33
             *  7 26 38 22 32 28 53 23 24 54 27 78 33
             *  7 26 38 22 24 28 53 23 32 54 27 78 33
             *  7 26 38 22 24 28 53 23 32 54 27 78 33
             *  7 26 27 22 24 28 38 23 32 54 53 78 33
             *  7 26 27 22 24 28 38 23 32 54 53 78 33
             *  7 26 27 22 24 28 38 23 32 54 53 78 33
             *  本轮结果:
             *  7 26 27 22 24 28 38 23 32 54 53 78 33
             *  gap=1
             *  7 26 27 22 24 28 38 23 32 54 53 78 33
             *  7 26 27 22 24 28 38 23 32 54 53 78 33
             *  7 22 26 27 24 28 38 23 32 54 53 78 33
             *  7 22 24 26 27 28 38 23 32 54 53 78 33
             *  7 22 24 26 27 28 38 23 32 54 53 78 33
             *  7 22 24 26 27 28 38 23 32 54 53 78 33
             *  7 22 23 24 26 27 28 38 32 54 53 78 33
             *  7 22 23 24 26 27 28 32 38 54 53 78 33
             *  7 22 23 24 26 27 28 32 38 54 53 78 33
             *  7 22 23 24 26 27 28 32 38 53 54 78 33
             *  7 22 23 24 26 27 28 32 38 53 54 78 33
             *  7 22 23 24 26 27 28 32 33 38 53 54 78
             *  本轮结果:
             *  7 22 23 24 26 27 28 32 33 38 53 54 78
             */

            int[]         arr_ses = { 7, 26, 53, 22, 32, 28, 38, 23, 24, 54, 27, 78, 33 };
            SelectionSort ses     = new SelectionSort();

            Console.WriteLine("选择排序:");
            ses.MySelectionSort(arr_ses);

            /*result
             *  7 26 53 22 32 28 38 23 24 54 27 78 33
             *  7 22 53 26 32 28 38 23 24 54 27 78 33
             *  7 22 23 53 32 28 38 26 24 54 27 78 33
             *  7 22 23 24 53 32 38 28 26 54 27 78 33
             *  7 22 23 24 26 53 38 32 28 54 27 78 33
             *  7 22 23 24 26 27 53 38 32 54 28 78 33
             *  7 22 23 24 26 27 28 53 38 54 32 78 33
             *  7 22 23 24 26 27 28 32 53 54 38 78 33
             *  7 22 23 24 26 27 28 32 33 54 53 78 38
             *  7 22 23 24 26 27 28 32 33 38 54 78 53
             *  7 22 23 24 26 27 28 32 33 38 53 78 54
             *  7 22 23 24 26 27 28 32 33 38 53 54 78
             */

            int[]    arr_hs = { 7, 26, 53, 22, 32, 28, 38, 23, 24, 54, 27, 78, 33 };
            HeapSort hs     = new HeapSort();

            Console.WriteLine("堆排序:");
            hs.MyHeapSort(arr_hs);

            /*result
             *  33 54 7 24 26 53 38 23 22 32 27 28 78
             *  28 33 53 24 32 7 38 23 22 26 27 54 78
             *  27 33 28 24 32 7 38 23 22 26 53 54 78
             *  26 33 27 24 32 7 28 23 22 38 53 54 78
             *  22 26 28 24 32 7 27 23 33 38 53 54 78
             *  23 22 28 24 26 7 27 32 33 38 53 54 78
             *  27 26 23 24 22 7 28 32 33 38 53 54 78
             *  7 26 23 24 22 27 28 32 33 38 53 54 78
             *  22 7 23 24 26 27 28 32 33 38 53 54 78
             *  7 22 23 24 26 27 28 32 33 38 53 54 78
             *  7 22 23 24 26 27 28 32 33 38 53 54 78
             *  7 22 23 24 26 27 28 32 33 38 53 54 78
             */

            int[]     arr_ms = { 7, 26, 53, 22, 32, 28, 38, 23, 24, 54, 27, 78, 33 };
            MergeSort ms     = new MergeSort();

            Console.WriteLine("归并排序:");
            ms.MyMergeSort(arr_ms);

            /*result
             *  26 53
             *  7 26 53
             *  28 32
             *  22 28 32
             *  7 22 26 28 32 53
             *  23 24
             *  23 24 38
             *  27 54
             *  33 78
             *  27 33 54 78
             *  23 24 27 33 38 54 78
             *  7 22 23 24 26 27 28 32 33 38 53 54 78
             */

            int[]        arr_cs = { 7, 26, 53, 22, 32, 28, 38, 23, 24, 54, 27, 78, 33 };
            CountingSort cs     = new CountingSort();

            Console.WriteLine("计数排序1:");
            cs.MyCountingSort(arr_cs);

            /*result
             *  数组最小值:7
             *  数组最大值:78
             *  每个元素个数统计:1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 1 0 1 1 1 0 0 0 1 1 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1
             *  每个元素值及比它值小的所有元素的个数统计:1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 2 3 4 4 5 6 7 7 7 7 8 9 9 9 9 9 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 11 12 12 12 12 12 12 12 12 12 12 12 12 12 12 12 12 12 12 12 12 12 12 12 12 13
             *  7 22 23 24 26 27 28 32 33 38 53 54 78
             */
            int[] arr_cs2 = { 7, 26, 53, 22, 32, 28, 38, 23, 24, 54, 27, 78, 33 };
            Console.WriteLine("计数排序2:");
            cs.MyCountingSort2(arr_cs2);

            /*result
             *  数组最小值:7
             *  数组最大值:78
             *  每个元素个数统计:0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 1 0 1 1 1 0 0 0 1 1 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1
             *  7 22 23 24 26 27 28 32 33 38 53 54 78
             */

            int[]      arr_bus = { 7, 26, 53, 22, 32, 28, 38, 23, 24, 54, 27, 78, 33 };
            BucketSort bus     = new BucketSort();

            Console.WriteLine("桶排序:");
            bus.MyBucketSort(arr_bus);

            /*result
             *  平方根:2 5 7 4 5 5 6 4 4 7 5 8 5
             *  数组最小值:2
             *  数组最大值:8
             *  桶内元素:
             *  7 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1
             *  22 23 24 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1
             *  26 32 28 27 33 -1 -1 -1 -1 -1 -1 -1 -1
             *  38 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1
             *  53 54 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1
             *  78 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1
             *  第2个桶内快排:-1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 7
             *  第4个桶内快排:-1 -1 -1 -1 -1 -1 -1 -1 -1 -1 22 23 24
             *  第5个桶内快排:-1 -1 -1 -1 -1 -1 -1 -1 26 27 28 32 33
             *  第6个桶内快排:-1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 38
             *  第7个桶内快排:-1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 53 54
             *  第8个桶内快排:-1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 78
             *  排序结果:7 22 23 24 26 27 28 32 33 38 53 54 78
             */

            int[]     arr_rs = { 7, 26, 53, 22, 32, 28, 38, 23, 24, 54, 27, 78, 33 };
            RadixSort rs     = new RadixSort();

            Console.WriteLine("基数排序:");
            rs.MyRadixSort(arr_rs);

            /*result
             *  桶内:22 32 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1
             *  53 23 33 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1
             *  24 54 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1
             *  26 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1
             *  7 27 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1
             *  28 38 78 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1
             *  桶外:22 32 53 23 33 24 54 26 7 27 28 38 78
             *  桶内:7 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1
             *  22 23 24 26 27 28 -1 -1 -1 -1 -1 -1 -1
             *  32 33 38 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1
             *  53 54 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1
             *  78 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1
             *  桶外:7 22 23 24 26 27 28 32 33 38 53 54 78
             */

            Console.WriteLine("");
            Console.WriteLine("");
            int[] arr_s = { 7, 22, 23, 24, 26, 27, 28, 32, 33, 38, 53, 54, 78 };
            int   index;

            SequenceSearch ss = new SequenceSearch();

            Console.WriteLine("顺序查找:");
            index = ss.MySequenceSearch(arr_s, 53);
            Console.WriteLine("查找成功: " + index);
            index = ss.MySequenceSearch(arr_s, 52);
            Console.WriteLine("查找失败: " + index);

            /*result
             *  比较第11次
             *  查找成功: 10
             *  比较第13次
             *  查找失败: -1
             */

            BinarySearch bis = new BinarySearch();

            Console.WriteLine("二分查找1:");
            index = bis.MyBinarySearch(arr_s, 53);
            Console.WriteLine("查找成功: " + index);
            index = bis.MyBinarySearch(arr_s, 52);
            Console.WriteLine("查找失败: " + index);
            Console.WriteLine("二分查找2:");
            index = bis.MyBinarySearch2(arr_s, 53, 0, arr_s.Length - 1);
            Console.WriteLine("查找成功: " + index);
            index = bis.MyBinarySearch2(arr_s, 52, 0, arr_s.Length - 1);
            Console.WriteLine("查找失败: " + index);

            /*result
             *  low-high:7-12
             *  low-high:10-12
             *  low-high:10-10
             *  mid:10
             *  查找成功: 10
             *  low-high:7-12
             *  low-high:10-12
             *  low-high:10-10
             *  low-high:10-9
             *  查找失败: -1
             */

            InterpolationSearch ints = new InterpolationSearch();

            Console.WriteLine("插值查找1:");
            index = ints.MyInterpolationSearch(arr_s, 53);
            Console.WriteLine("查找成功: " + index);
            index = ints.MyInterpolationSearch(arr_s, 52);
            Console.WriteLine("查找失败: " + index);
            index = ints.MyInterpolationSearch2(arr_s, 53, 0, arr_s.Length - 1);
            Console.WriteLine("查找成功: " + index);
            index = ints.MyInterpolationSearch2(arr_s, 52, 0, arr_s.Length - 1);
            Console.WriteLine("查找失败: " + index);

            /*result
             *  low-high:8-12
             *  low-high:10-12
             *  mid:10
             *  查找成功: 10
             *  low-high:8-12
             *  low-high:10-12
             *  low-high:10-9
             *  查找失败: -1
             */

            FibonacciSearch fs = new FibonacciSearch();

            Console.WriteLine("斐波那契查找1:");
            index = fs.MyFibonacciSearch(arr_s, 53);
            Console.WriteLine("查找成功: " + index);
            index = fs.MyFibonacciSearch(arr_s, 52);
            Console.WriteLine("查找失败: " + index);
            Console.WriteLine("斐波那契查找2:");
            index = fs.MyFibonacciSearch2(arr_s, 53);
            Console.WriteLine("查找成功: " + index);
            index = fs.MyFibonacciSearch(arr_s, 52);
            Console.WriteLine("查找失败: " + index);

            /*result
             *  斐波那契数列:0 1 1 2 3 5 8 13 21
             *  扩展后的数组:7 22 23 24 26 27 28 32 33 38 53 54 78 78 78 78 78 78 78 78
             *  low-high-k:0-11-7
             *  low-high-k:8-11-5
             *  mid-k:10-5
             *  查找成功: 10
             *  斐波那契数列:0 1 1 2 3 5 8 13 21
             *  扩展后的数组:7 22 23 24 26 27 28 32 33 38 53 54 78 78 78 78 78 78 78 78
             *  low-high-k:0-11-7
             *  low-high-k:8-11-5
             *  low-high-k:8-9-4
             *  low-high-k:10-9-2
             *  查找失败: -1
             */

            BlockSearch bls = new BlockSearch();

            Console.WriteLine("分块查找:");
            index = bls.MyBlockSearch(arr_s, 53, 4);
            Console.WriteLine("查找成功: " + index);
            index = bls.MyBlockSearch(arr_s, 52, 4);
            Console.WriteLine("查找失败: " + index);

            /*result
             *  序列数组:
             *  7 22 23 24
             *  26 27 28 32
             *  33 38 53 54
             *  78
             *  最小值最大值:
             *  7 26 33 78 24 32 54 78
             *  low-high:2-3
             *  mid:2
             *  查找成功: 10
             *
             *  序列数组:
             *  7 22 23 24
             *  26 27 28 32
             *  33 38 53 54
             *  78
             *  最小值最大值:
             *  7 26 33 78 24 32 54 78
             *  low-high:2-3
             *  low-high:2-1
             *  查找失败: -1
             */

            int[]            arr_bts = { 32, 24, 54, 22, 27, 38, 78, 7, 23, 26, 28, 33, 53 };
            BinaryTreeSearch bts     = new BinaryTreeSearch();

            Console.WriteLine("二叉树查找1:");
            index = bts.MyBinaryTreeSearch(arr_bts, 53);
            Console.WriteLine("查找成功: " + index);
            index = bts.MyBinaryTreeSearch(arr_bts, 52);
            Console.WriteLine("查找失败: " + index);
            Console.WriteLine("二叉树查找2:");
            index = bts.MyBinaryTreeSearch2(arr_bts, 53, 0, 0);
            Console.WriteLine("查找成功: " + index);
            index = bts.MyBinaryTreeSearch2(arr_bts, 52, 0, 0);
            Console.WriteLine("查找失败: " + index);

            /*result
             *  第1次比较:i-0 arr[i]-32
             *  第2次比较:i-2 arr[i]-54
             *  第3次比较:i-5 arr[i]-38
             *  第4次比较:i-12 arr[i]-53
             *  查找成功: 12
             *  第1次比较:i-0 arr[i]-32
             *  第2次比较:i-2 arr[i]-54
             *  第3次比较:i-5 arr[i]-38
             *  第4次比较:i-12 arr[i]-53
             *  查找失败: -1
             */

            Console.ReadKey();
        }
예제 #15
0
        public void SelectionSort_Descending_Ascending()
        {
            var reversed = Enumerable.Range(1, 10_000).Reverse().ToArray();

            SelectionSort <int> .Sort(reversed).Should().BeInAscendingOrder();
        }
예제 #16
0
        private void button1_Click(object sender, EventArgs e)
        {
            int[] arr = new DiziOlustur().Olustur();


            var secim = algoritmaListesi.SelectedIndex;

            if (secim == 0)
            {
                SelectionSort selectionSort = new SelectionSort(arr);
                Stopwatch     stopwatch     = new Stopwatch();
                stopwatch.Start();
                selectionSort.SelectionSortAlgoritm();
                stopwatch.Stop();
                TimeSpan sure = stopwatch.Elapsed;
                lblSelection.Text = sure.ToString();
            }
            else if (secim == 1)
            {
                InsertionSort insertionSort = new InsertionSort(arr);
                Stopwatch     stopwatch     = new Stopwatch();
                stopwatch.Start();
                insertionSort.insertion_sort();
                stopwatch.Stop();
                TimeSpan sure = stopwatch.Elapsed;
                lblInsertion.Text = sure.ToString();
            }
            else if (secim == 2)
            {
                BubbleSort bubbleSort = new BubbleSort(arr);
                Stopwatch  stopwatch  = new Stopwatch();
                stopwatch.Start();
                bubbleSort.Bubble_Sort();
                stopwatch.Stop();
                TimeSpan sure = stopwatch.Elapsed;
                lblBubble.Text = sure.ToString();
            }
            else if (secim == 3)
            {
                CountingSort countingSort = new CountingSort(arr);
                Stopwatch    stopwatch    = new Stopwatch();
                stopwatch.Start();
                countingSort.Counting_Sort();
                stopwatch.Stop();
                TimeSpan sure = stopwatch.Elapsed;
                lblCounting.Text = sure.ToString();
            }
            else if (secim == 4)
            {
                QuickSort quickSort = new QuickSort(arr);
                Stopwatch stopwatch = new Stopwatch();
                stopwatch.Start();
                quickSort.sort_quick();
                stopwatch.Stop();
                TimeSpan sure = stopwatch.Elapsed;
                lblQuick.Text = sure.ToString();
            }
            else if (secim == 5)
            {
                MergeSort mergeSort = new MergeSort(arr);
                Stopwatch stopwatch = new Stopwatch();
                stopwatch.Start();
                mergeSort.sort_merge();
                stopwatch.Stop();
                TimeSpan sure = stopwatch.Elapsed;
                lblMerge.Text = sure.ToString();
            }
        }
예제 #17
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();
     }
 }
예제 #18
0
 private void Ss_FormClosed(object sender, FormClosedEventArgs e)
 {
     ss = null;
 }
예제 #19
0
 public void SelectionSort_Sort_Success(int[] data)
 {
     SelectionSort.Sort(data);
     Assert.True(data.IsSorted());
 }
예제 #20
0
 private void Awake()
 {
     Instance = this;
 }
예제 #21
0
 public TestSelectionSort()
 {
     _selectionSort = new SelectionSort();
     _expected      = new[] { -7, -5, -2, -1, 0, 2, 3, 6, 8, 10 };
 }
예제 #22
0
 public SelectionSortTest()
 {
     _sut = new SelectionSort();
 }
        public void ShouldNotBeNull()
        {
            var sut = new SelectionSort();

            Assert.Throws <ArgumentNullException>(() => sut.Sort(null));
        }
예제 #24
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]);
                }
            }
        }
예제 #25
0
 public void Setup()
 {
     this.selectionSort  = new SelectionSort();
     this.arrayGenerator = new ArrayGenerator();
 }
예제 #26
0
 public void Initialize()
 {
     Sorter = new SelectionSort();
 }
예제 #27
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
        }
예제 #28
0
 public void SortTest_NullArray()
 {
     SelectionSort.Sort(null);
 }
        //################################################################################
        #region ISortStrategy Implementation

        void ISortStrategy.Sort(int[] unsortedList)
        {
            SelectionSort selectionSortAlgorithm = new SelectionSort(unsortedList);

            selectionSortAlgorithm.Sort();
        }
예제 #30
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);
        }
예제 #31
0
        private void AllSortButton_Click(object sender, EventArgs e)
        {
            SortDatarichTextBox.Text = "Calculating ... Wait a moment ...";
            BubbleLabel.Text         = "Time: ";
            SelectionLabel.Text      = "Time: ";
            CocktailLabel.Text       = "Time: ";
            GnomeLabel.Text          = "Time: ";
            HeapLabel.Text           = "Time: ";
            InsertionLabel.Text      = "Time: ";
            LSDLabel.Text            = "Time: ";
            MSDLabel.Text            = "Time: ";
            MergeLabel.Text          = "Time: ";
            QuickLabel.Text          = "Time: ";
            ShellLabel.Text          = "Time: ";
            TreeLabel.Text           = "Time: ";
            SortDatarichTextBox.Text = "";
            var min = new List <BaseAlgorithm <int> >();

            if (Collection.Count < 10001)
            {
                var bubble = new BubbleSort <int>(Collection, "BubbleSort");
                bubble.Sort();
                BubbleLabel.Text += bubble.Time.ToString();
                min.Add(bubble);
            }
            if (Collection.Count < 10001)
            {
                var selection = new SelectionSort <int>(Collection, "SelectionSort");
                selection.Sort();
                SelectionLabel.Text += selection.Time.ToString();
                min.Add(selection);
            }
            if (Collection.Count < 10001)
            {
                var cocktail = new CocktailSort <int>(Collection, "CocktailSort");
                cocktail.Sort();
                CocktailLabel.Text += cocktail.Time.ToString();
                min.Add(cocktail);
            }
            if (Collection.Count < 10001)
            {
                var Gnome = new GnomeSort <int>(Collection, "GnomeSort");
                Gnome.Sort();
                GnomeLabel.Text += Gnome.Time.ToString();
                min.Add(Gnome);
            }
            if (Collection.Count < 10001)
            {
                var Insertion = new InsertionSort <int>(Collection, "InsertionSort");
                Insertion.Sort();
                InsertionLabel.Text += Insertion.Time.ToString();
                min.Add(Insertion);
            }
            var Tree = new TreeSort <int>(Collection, "TreeSort");

            Tree.Sort();
            TreeLabel.Text += Tree.Time.ToString();
            min.Add(Tree);
            var Heap = new HeapSort <int>(Collection, "HeapSort");

            Heap.Sort();
            HeapLabel.Text += Heap.Time.ToString();
            min.Add(Heap);
            var LSDRadix = new LSDRadixSort <int>(Collection, "LSDRadixSort");

            LSDRadix.Sort();
            LSDLabel.Text += LSDRadix.Time.ToString();
            min.Add(LSDRadix);
            var MSDRadix = new MSDRadixSort <int>(Collection, "MSDRadixSort");

            MSDRadix.Sort();
            MSDLabel.Text += MSDRadix.Time.ToString();
            min.Add(MSDRadix);
            var Merge = new MergeSort <int>(Collection, "MergeSort");

            Merge.Sort();
            MergeLabel.Text += Merge.Time.ToString();
            min.Add(Merge);
            var Quick = new QuickSort <int>(Collection, "QuickSort");

            Quick.Sort();
            QuickLabel.Text += Quick.Time.ToString();
            min.Add(Quick);
            var Shell = new ShellSort <int>(Collection, "ShellSort");

            Shell.Sort();
            ShellLabel.Text += Shell.Time.ToString();
            min.Add(Shell);
            var best = GetMinTime(min);

            SortDatarichTextBox.Text = $"THE BEST:\n" + best.Name + $"\n{best.Time}";
        }
예제 #32
0
        public void SelectionSortTest()
        {
            var sorter = new SelectionSort(ToSortList());

            SortTest(sorter);
        }