public void InsertSortTest()
        {
            // Random elements
            var sorter = new InsertionSort<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);
        }
Beispiel #2
0
        protected void btn_insertionSort_Click(object sender, EventArgs e)
        {
            int[] array = { 123, 14, 25, 47, 111, 1231231, 1242, 132312, 334234 };
            InsertionSort sortAlg = new InsertionSort(array);

            txt_beforeSort.Text = sortAlg.toString();
            sortAlg.Sort();
            txt_afterSort.Text = sortAlg.toString();
        }
 // Gets and sorts an array of integer data.
 public static void Main()
 {
     int size = GetSize();
     int[] item = GetData(size);
     ArrayCopy.Display("The data to sort is ", item);
     InsertionSort s = new InsertionSort(item);
     s.Sort();
     ArrayCopy.Display("The sorted data is ", item);
 }
        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();

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

            array = sort.Sort(array);

            Assert.IsTrue(TestHelpers<int>.IsSorted(array));
        }
Beispiel #5
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;
        }
        public void InsertionSortTest_Positive()
        {
            int    Min     = 0;
            int    Max     = 20;
            Random randNum = new Random();

            int[] input = Enumerable
                          .Repeat(Min, Max)
                          .Select(i => randNum.Next(Min, Max)).OrderByDescending(s => s).Distinct()
                          .ToArray();

            ISort     sort  = new InsertionSort();
            Stopwatch timer = new Stopwatch();

            timer.Start();
            int[] actual = sort.Sort(input);
            timer.Stop();
            input = input.OrderBy(s => s).ToArray();

            for (int expected = 0; expected < input.Length; expected++)
            {
                Assert.AreEqual(input[expected], actual[expected]);
            }
        }
Beispiel #7
0
        static void Main(string[] args)
        {
            int[] arr1 = { 31, 15, 10, 2, 4, 2, 14, 23, 12, 66 };

            StrategySort sort    = new SelectionSort();
            Context      context = new Context(sort, arr1);

            context.Sort();
            context.PrintArray();

            int[] arr2 = { 1, 5, 10, 2, 4, 12, 14, 23, 12, 66 };

            sort    = new InsertionSort();
            context = new Context(sort, arr2);

            context.Sort();
            context.PrintArray();

            int[] arr3 = { 1, 8, 4, 7, 3, 7, 1, 6 };
            sort    = new BubleSort();
            context = new Context(sort, arr3);
            context.Sort();
            context.PrintArray();
        }
Beispiel #8
0
        /// <summary>
        /// Sortiert die eingebenen Zahlen mithilfe des Insertion Sorts
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ButtonInsertion_Click(object sender, EventArgs e)
        {
            numbers = GetArrayFromForm();
            sw.Start();
            InsertionSort insertionSort = new InsertionSort();
            StringBuilder stringBuilder = new StringBuilder();

            int[] array = insertionSort.Run(numbers);
            sw.Stop();

            foreach (var element in array)
            {
                stringBuilder.Append(element.ToString() + " ");
            }
            textBoxOutput.Text = stringBuilder.ToString();

            if (checkBoxTesting.Checked)
            {
                labelValid.Text = "Valid: " + testing.Run(array).ToString();
            }
            textBoxLog.Text += "Insertion Zeit: " + sw.Elapsed + "\r\n";
            Console.WriteLine("Insertion Zeit: " + sw.Elapsed);
            sw.Reset();
        }
Beispiel #9
0
        /// <summary>
        /// Testet ob der Insertion Sort Mechanismus funktioniert
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ButtonInsertionTest_Click(object sender, EventArgs e)
        {
            sw.Start();
            bool   valid  = true;
            Random random = new Random();

            for (int i = 0; i < 1000; i++)
            {
                numbers = new int[3000];
                for (int x = 0; x < 3000; x++)
                {
                    numbers[x] = random.Next(100, 100000);
                }
                InsertionSort insertionSort = new InsertionSort();
                int[]         array         = insertionSort.Run(numbers);
                valid = testing.Run(array);
            }

            sw.Stop();
            textBoxLog.Text += "Insertion Testing Zeit: " + sw.Elapsed + "\r\n";
            Console.WriteLine("Insertion Testing - Zeit: " + sw.Elapsed);
            Console.WriteLine("Valid: " + valid);
            sw.Reset();
        }
Beispiel #10
0
        public DoublingInsertion(int numberOfElements)
        {
            var numArray = generateIntArray(numberOfElements);

            InsertionSort.sort(numArray);
        }
Beispiel #11
0
        public static void RunEdgeCases()
        {
            // Create a string builder to hold the log messages
            var sb = new StringBuilder();

            _writeMessage("ITCS 6114 Algorithms & Data Structures Assignment 1: Edge Cases", sb);
            _writeMessage("This will take a while! When this program finishes execution, a CSV will be produced in this directory displaying the outputs.", sb);

            // Create two lists of CSV records, one for each edge case
            var csvSortedRecords   = new List <CSVRecord>();
            var csvReversedRecords = new List <CSVRecord>();
            // Create list of input sizes
            var inputSizes = new int[] { 10, 100, 1000, 1500, 2000, 2500, 4000, 4500, 5000, 7500, 10000, 15000, 20000, 25000, 30000, 35000, 40000, 45000, 50000, 100000 };
            // Create stopwatch
            var stopWatch = new Stopwatch();
            // Create rng
            var rand = new Random();

            // Run 5 iterations
            for (int i = 1; i <= 5; i++)
            {
                _writeMessage($"Starting Test Iteration {i}", sb);
                // Run for each input size
                foreach (var n in inputSizes)
                {
                    var sortedRecord = new CSVRecord {
                        Iteration = i, NumElements = n
                    };
                    var reversedRecord = new CSVRecord {
                        Iteration = i, NumElements = n
                    };
                    _writeMessage($"\tInput Size n = {n}", sb);
                    _writeMessage($"\tGenerating {n} random numbers", sb);
                    var lowestToHighest = Enumerable.Range(0, n).ToList();
                    var highestToLowest = Enumerable.Range(0, n).ToList();
                    highestToLowest.Reverse();

                    // Test Insertion Sort with sorted List
                    _writeMessage($"\t\tStarting Insertion Sort with sorted List of n = {n}", sb);
                    _writeMessage("\t\t\tRunning...", sb);
                    stopWatch.Restart();

                    var insertionResults = InsertionSort.Sort(lowestToHighest);

                    stopWatch.Stop();
                    sortedRecord.InsertionSortTime = stopWatch.ElapsedMilliseconds;
                    _writeMessage($"\t\t\tCompleted Insertion Sort with sorted List of n = {n} with {stopWatch.ElapsedMilliseconds}ms", sb);
                    _writeMessage("\t\t\tVerifying sort results...", sb);
                    bool insertionSuccess = _isSortCorrect(insertionResults);
                    if (insertionSuccess)
                    {
                        _writeMessage("\t\t\tSort results verified!", sb);
                    }
                    else
                    {
                        _writeMessage("\t\t\tSort Failed!", sb);
                        return;
                    }

                    _writeMessage($"\t\tStarting Insertion Sort with reversed List of n = {n}", sb);
                    _writeMessage("\t\t\tRunning...", sb);
                    stopWatch.Restart();

                    insertionResults = InsertionSort.Sort(highestToLowest);

                    stopWatch.Stop();
                    reversedRecord.InsertionSortTime = stopWatch.ElapsedMilliseconds;
                    _writeMessage($"\t\t\tCompleted Insertion Sort with reversed List of n = {n} with {stopWatch.ElapsedMilliseconds}ms", sb);
                    _writeMessage("\t\t\tVerifying sort results...", sb);
                    insertionSuccess = _isSortCorrect(insertionResults);
                    if (insertionSuccess)
                    {
                        _writeMessage("\t\t\tSort results verified!", sb);
                    }
                    else
                    {
                        _writeMessage("\t\t\tSort Failed!", sb);
                        return;
                    }

                    // Test Merge Sort
                    _writeMessage($"\t\tStarting Merge Sort with sorted List of n = {n}", sb);
                    _writeMessage("\t\t\tRunning...", sb);
                    stopWatch.Restart();

                    var MergeResults = MergeSort <int> .Sort(lowestToHighest);

                    stopWatch.Stop();
                    sortedRecord.MergeSortTime = stopWatch.ElapsedMilliseconds;
                    _writeMessage($"\t\t\tCompleted Merge Sort with sorted List of n = {n} with {stopWatch.ElapsedMilliseconds}ms", sb);
                    _writeMessage("\t\t\tVerifying sort results...", sb);
                    bool mergeSuccess = _isSortCorrect(MergeResults);
                    if (mergeSuccess)
                    {
                        _writeMessage("\t\t\tSort results verified!", sb);
                    }
                    else
                    {
                        _writeMessage("\t\t\tSort Failed!", sb);
                        return;
                    }

                    _writeMessage($"\t\tStarting Merge Sort with reversed List of n = {n}", sb);
                    _writeMessage("\t\t\tRunning...", sb);
                    stopWatch.Restart();

                    MergeResults = MergeSort <int> .Sort(highestToLowest);

                    stopWatch.Stop();
                    reversedRecord.MergeSortTime = stopWatch.ElapsedMilliseconds;
                    _writeMessage($"\t\t\tCompleted Merge Sort with reversed List of n = {n} with {stopWatch.ElapsedMilliseconds}ms", sb);
                    _writeMessage("\t\t\tVerifying sort results...", sb);
                    mergeSuccess = _isSortCorrect(MergeResults);
                    if (mergeSuccess)
                    {
                        _writeMessage("\t\t\tSort results verified!", sb);
                    }
                    else
                    {
                        _writeMessage("\t\t\tSort Failed!", sb);
                        return;
                    }

                    // Test Heap Sort
                    _writeMessage($"\t\tStarting Heap Sort with worted List of n = {n}", sb);
                    _writeMessage("\t\t\tRunning...", sb);
                    stopWatch.Restart();

                    var heapResults = HeapSort.Sort(lowestToHighest);

                    stopWatch.Stop();
                    sortedRecord.HeapSortTime = stopWatch.ElapsedMilliseconds;
                    _writeMessage($"\t\t\tCompleted Heap Sort with sorted List of n = {n} with {stopWatch.ElapsedMilliseconds}ms", sb);
                    bool heapSuccess = _isSortCorrect(heapResults);
                    if (heapSuccess)
                    {
                        _writeMessage("\t\t\tSort results verified!", sb);
                    }
                    else
                    {
                        _writeMessage("\t\t\tSort Failed!", sb);
                        return;
                    }

                    _writeMessage($"\t\tStarting Heap Sort with reversed List of n = {n}", sb);
                    _writeMessage("\t\t\tRunning...", sb);
                    stopWatch.Restart();

                    heapResults = HeapSort.Sort(highestToLowest);

                    stopWatch.Stop();
                    reversedRecord.HeapSortTime = stopWatch.ElapsedMilliseconds;
                    _writeMessage($"\t\t\tCompleted Heap Sort with n = {n} with {stopWatch.ElapsedMilliseconds}ms", sb);
                    heapSuccess = _isSortCorrect(heapResults);
                    if (heapSuccess)
                    {
                        _writeMessage("\t\t\tSort results verified!", sb);
                    }
                    else
                    {
                        _writeMessage("\t\t\tSort Failed!", sb);
                        return;
                    }

                    // Test Quick Sort (In-Place)
                    _writeMessage($"\t\tStarting Quick Sort (In-Place) with sorted List of n = {n}", sb);
                    _writeMessage("\t\t\tRunning...", sb);
                    stopWatch.Restart();

                    var IPQuickSortResults = IPQuickSort <int> .Sort(lowestToHighest);

                    stopWatch.Stop();
                    sortedRecord.QuickSortInPlaceTime = stopWatch.ElapsedMilliseconds;
                    _writeMessage($"\t\t\tCompleted Quick Sort (In-Place) with sorted List of n = {n} with {stopWatch.ElapsedMilliseconds}ms", sb);
                    _writeMessage("\t\t\tVerifying sort results...", sb);
                    bool ipquickSuccess = _isSortCorrect(IPQuickSortResults);
                    if (ipquickSuccess)
                    {
                        _writeMessage("\t\t\tSort results verified!", sb);
                    }
                    else
                    {
                        _writeMessage("\t\t\tSort Failed!", sb);
                        return;
                    }

                    _writeMessage($"\t\tStarting Quick Sort (In-Place) with reversed List of n = {n}", sb);
                    _writeMessage("\t\t\tRunning...", sb);
                    stopWatch.Restart();

                    IPQuickSortResults = IPQuickSort <int> .Sort(highestToLowest);

                    stopWatch.Stop();
                    reversedRecord.QuickSortInPlaceTime = stopWatch.ElapsedMilliseconds;
                    _writeMessage($"\t\t\tCompleted Quick Sort (In-Place) with reversed List of n = {n} with {stopWatch.ElapsedMilliseconds}ms", sb);
                    _writeMessage("\t\t\tVerifying sort results...", sb);
                    ipquickSuccess = _isSortCorrect(IPQuickSortResults);
                    if (ipquickSuccess)
                    {
                        _writeMessage("\t\t\tSort results verified!", sb);
                    }
                    else
                    {
                        _writeMessage("\t\t\tSort Failed!", sb);
                        return;
                    }

                    // Test Quick Sort (Modified)
                    _writeMessage($"\t\tStarting Quick Sort (Modified) with sorted List of n = {n}", sb);
                    _writeMessage("\t\t\tRunning...", sb);
                    stopWatch.Restart();

                    var ModQuickSortResults = ModQuickSort <int> .Sort(lowestToHighest);

                    stopWatch.Stop();
                    sortedRecord.QuickSortModifiedTime = stopWatch.ElapsedMilliseconds;
                    _writeMessage($"\t\t\tCompleted Quick Sort (Modified) with sorted List of n = {n} with {stopWatch.ElapsedMilliseconds}ms", sb);
                    _writeMessage("\t\t\tVerifying sort results...", sb);
                    bool modquickSuccess = _isSortCorrect(ModQuickSortResults);
                    if (modquickSuccess)
                    {
                        _writeMessage("\t\t\tSort results verified!", sb);
                    }
                    else
                    {
                        _writeMessage("\t\t\tSort Failed!", sb);
                        return;
                    }

                    _writeMessage($"\t\tStarting Quick Sort (Modified) with reversed List of n = {n}", sb);
                    _writeMessage("\t\t\tRunning...", sb);
                    stopWatch.Restart();

                    ModQuickSortResults = ModQuickSort <int> .Sort(lowestToHighest);

                    stopWatch.Stop();
                    reversedRecord.QuickSortModifiedTime = stopWatch.ElapsedMilliseconds;
                    _writeMessage($"\t\t\tCompleted Quick Sort (Modified) with reversed List of n = {n} with {stopWatch.ElapsedMilliseconds}ms", sb);
                    _writeMessage("\t\t\tVerifying sort results...", sb);
                    modquickSuccess = _isSortCorrect(ModQuickSortResults);
                    if (modquickSuccess)
                    {
                        _writeMessage("\t\t\tSort results verified!", sb);
                    }
                    else
                    {
                        _writeMessage("\t\t\tSort Failed!", sb);
                        return;
                    }

                    csvSortedRecords.Add(sortedRecord);
                    csvReversedRecords.Add(reversedRecord);
                }
                _writeMessage($"Concluded Test Iteration {i}", sb);
            }

            _writeMessage("All sorting tests concluded! Please check the project directory for the sorting_results.csv and output.txt files.", sb);

            Console.WriteLine("Writing to sorting_results.csv ...");

            // Write results to CSV
            using (var writer = new StreamWriter("sorting_sorted_results.csv"))
                using (var csv = new CsvWriter(writer))
                {
                    csv.WriteRecords <CSVRecord>(csvSortedRecords);
                }

            using (var writer = new StreamWriter("sorting_reversed_results.csv"))
                using (var csv = new CsvWriter(writer))
                {
                    csv.WriteRecords <CSVRecord>(csvReversedRecords);
                }

            Console.WriteLine("Writing to output-edgecases.txt ...");

            using (var writer = new StreamWriter("output-edgecases.txt"))
            {
                writer.Write(sb.ToString());
            }

            Console.WriteLine("All writing successful!");
        }
Beispiel #12
0
 public Insertion_Sort()
 {
     insertionBehavior = new InsertionSort();
 }
Beispiel #13
0
        static void BubbleVsInsertionSort()
        {
            GenerateMockData();

            var reader = new Reader();
            var writer = new Writer();

            var insertionSort = new InsertionSort();
            var bubbleSort    = new BubbleSort();

            var endProgram = false;

            while (!endProgram)
            {
                Console.WriteLine("Press  a  generate mock data.");
                Console.WriteLine("Press  b  to bubble sort");
                Console.WriteLine("Press  c  to insertion sort");
                Console.WriteLine("Press  d  to end program");

                var pressedKey = Console.ReadLine();

                if (pressedKey == "a")
                {
                    GenerateMockData();

                    Console.WriteLine("Operation finished");

                    continue;
                }
                if (pressedKey == "b")
                {
                    var data = reader.Read();

                    Stopwatch stopWatch = new Stopwatch();
                    stopWatch.Start();

                    data = bubbleSort.Sort(data);
                    stopWatch.Stop();
                    Console.WriteLine("Time elapsed: " + stopWatch.Elapsed);

                    Console.WriteLine("Sorting done, swap number: " + bubbleSort.SwapCounter);

                    Console.WriteLine("Writting data");

                    writer.WriteDataInFile(data, "bubbleOutput.txt");

                    Console.WriteLine("Operation finished");


                    continue;
                }
                if (pressedKey == "c")
                {
                    var data = reader.Read();


                    Stopwatch stopWatch = new Stopwatch();
                    stopWatch.Start();

                    data = insertionSort.Sort(data);

                    stopWatch.Stop();
                    Console.WriteLine("Time elapsed: " + stopWatch.Elapsed);

                    Console.WriteLine("Sorting done, swap number: " + insertionSort.SwapCounter);

                    Console.WriteLine("Writting data");

                    writer.WriteDataInFile(data, "insertionOutput.txt");

                    Console.WriteLine("Operation finished");


                    continue;
                }
                if (pressedKey == "d")
                {
                    endProgram = true;

                    continue;
                }


                Console.WriteLine();
                Console.WriteLine();
            }
        }
Beispiel #14
0
 public void Given_NullOrEmptyArray_Expected_ThrowsArgumentException(int[] d)
 {
     Assert.Throws <ArgumentException>(() => InsertionSort.Sort(d));
 }
Beispiel #15
0
        static void Main(string[] args)
        {
            LinkTest.LinkedListTest();



            const int count   = 50000;
            int       max     = 100000;
            int       arrCout = 10;

            int[]        A     = new int[count];
            int[]        B     = new int[count];
            List <int[]> listA = new List <int[]>()
            {
            };
            List <int[]> listB = new List <int[]>()
            {
            };

            for (int i = 0; i < arrCout; i++)
            {
                listA.Add(new int[count]);
                listB.Add(new int[count]);
            }
            A = Util.GenerateRandomArray(count, 0, max);
            B = Util.GenerateNearlyOrderedArray(count, arrCout);
            for (int i = 0; i < listA.Count; i++)
            {
                A.CopyTo(listA[i], 0);
                B.CopyTo(listB[i], 0);
            }

            var array = new int[10] {
                0, 9, 8, 7, 6, 5, 4, 3, 2, 1,
            };

            Merge.MergeSort(array);
            var array2 = new int[10] {
                9, 8, 7, 6, 5, 9, 4, 3, 2, 1,
            };

            Quick.QuickSort(listA[0]);
            var isSort = Util.IsSortForInt(listA[0]);
            var v0     = Bubble.BubbleSortFunc(listA[0]);

            isSort = Util.IsSortForInt(listA[0]);
            Console.WriteLine($"BubbleSortFunc --{v0} -/mulriple = {v0.TotalSeconds*1000},---{isSort} ");

            v0     = Bubble.BubbleSortFuncOpt(listA[1]);
            isSort = Util.IsSortForInt(listA[1]);
            Console.WriteLine($"BubbleSortFuncOpt ----{v0} -/mulriple = {v0.TotalSeconds * 1000},---{isSort} ");

            v0     = InsertionSort.InsertionSortFunc(listA[2]);
            isSort = Util.IsSortForInt(listA[2]);
            Console.WriteLine($"InsertionSortFunc ----{v0}-/mulriple = {v0.TotalSeconds * 1000}---{isSort} ");

            v0     = InsertionSort.InsertionSortFunc(listA[3]);
            isSort = Util.IsSortForInt(listA[3]);
            Console.WriteLine($"InsertionSortFunc ----{v0}-/mulriple = {v0.TotalSeconds * 1000}---{isSort} ");

            v0     = InsertionSort.InsertionSortFuncOpt(listA[4]);
            isSort = Util.IsSortForInt(listA[4]);
            Console.WriteLine($"InsertionSortFuncOpt ----{v0} -/mulriple = {v0.TotalSeconds * 1000} ---{isSort} ");


            Console.WriteLine($"ShellSortFunc ----{v0} -/mulriple = {v0.TotalSeconds * 1000} ---{isSort} ");
            v0     = ShellSort.ShellSortFunc(listA[6], 2);
            isSort = Util.IsSortForInt(listA[6]);
            Console.WriteLine($"ShellSortFunc ----{v0} -/mulriple = {v0.TotalSeconds * 1000} ---{isSort} ");
            v0     = ShellSort.ShellSortFunc(listA[7], 4);
            isSort = Util.IsSortForInt(listA[7]);
            Console.WriteLine($"ShellSortFunc ----{v0} -/mulriple = {v0.TotalSeconds * 1000} ---{isSort} ");
            v0     = ShellSort.ShellSortFunc(listA[8], 5);
            isSort = Util.IsSortForInt(listA[8]);
            Console.WriteLine($"ShellSortFunc ----{v0} -/mulriple = {v0.TotalSeconds * 1000} ---{isSort} ");

            v0     = ShellSort.ShellSortFunc(listA[5]);
            isSort = Util.IsSortForInt(listA[5]);
            Console.WriteLine($"ShellSortFunc ----{v0} -/mulriple = {v0.TotalSeconds * 1000} ---{isSort} ");



            int N = 20;

            //

            // 创建一个数组,包含[0...N)的所有元素
            int[]     arr2 = new int[N];
            int[]     arr  = new int[N];
            Stopwatch sw   = new Stopwatch();

            string[] Srr = new string[N];
            for (int i = 0; i < N; i++)
            {
                arr2[i] = i;
                Srr[i]  = i.ToString();
            }
            // 打乱数组顺序
            Random s = new Random();

            for (int i = 0; i < N; i++)
            {
                int j = s.Next(0, N);
                arr[i] = arr2[j];
                Srr[i] = arr2[j].ToString();
            }
            // 实现的二分搜索树不是平衡二叉树,
            // 如果按照顺序插入一组数据,二分搜索树会退化成为一个链表
            // 平衡二叉树的实现---红黑树。


            // 我们测试用的的二分搜索树的键类型为Integer,值类型为String
            // 键值的对应关系为每个整型对应代表这个整型的字符串
            BST <int, String> bst  = new BST <int, String>();
            BST <int, String> bst2 = new BST <int, String>();

            sw.Start();
            for (int i = 0; i < N; i++)
            {
                bst.Insert(arr[i], arr[i].ToString());
            }
            sw.Stop(); TimeSpan ts10 = sw.Elapsed; sw.Restart(); Console.WriteLine(" one time is {0}", ts10.TotalMilliseconds);

            sw.Start();
            bst2.CreateBinarySearchTree(arr, Srr);
            sw.Stop(); TimeSpan ts2 = sw.Elapsed; sw.Restart(); Console.WriteLine(" two time is {0}", ts2.TotalMilliseconds);


            Console.WriteLine(bst.PreOrder());
            Console.WriteLine(bst.InOrder());
            Console.WriteLine(bst.PostOrder());

            Console.WriteLine("BFS" + bst.BFS());
            Console.WriteLine("DFS" + bst.DFS());
            //int sf = Convert.ToInt32(Console.ReadLine());
            //Console.WriteLine(bst.Ceil(sf));
            Console.WriteLine(bst.PreOrder());
            Console.WriteLine(bst.InOrder());
            Console.WriteLine(bst.PostOrder());

            // 对[0...2*N)的所有整型测试在二分搜索树中查找
            // 若i在[0...N)之间,则能查找到整型所对应的字符串
            // 若i在[N...2*N)之间,则结果为null

            /* 二叉搜索测试
             * for (int i = 0; i <  N; i++)
             * {
             *  String res = bst.Search(i);
             *  if (i < N) {
             *      if (res == i.ToString())
             *          Console.WriteLine(i+"----");
             *      if(res ==null)
             *      {
             *          Console.WriteLine(i+"+++");
             *      }
             *  }
             * }*/

            /*计算运行时间
             * //sw.Start()
             * //sw.Stop(); TimeSpan ts10 = sw.Elapsed; sw.Restart(); Console.WriteLine(" 列表方法 ListEquals time is {0}", ts10.TotalMilliseconds);
             * ////Console.WriteLine(jordan.ToString());
             */
            Console.ReadKey();
        }
Beispiel #16
0
 public void Should_Order_List_With_1_Element()
 {
     int [] array = { 1 };
     Assert.Equal(InsertionSort.Sort(array), array);
 }
Beispiel #17
0
 public void Should_Order_Empty_List()
 {
     Assert.Equal(InsertionSort.Sort(new int[0]), new int[0]);
 }
Beispiel #18
0
    void OnGUI()
    {
        if (GUILayout.Button("Code Time Test"))
        {
            content1 = codeTimeTest();
            content2 = "";
            content3 = "";
        }

        GUILayout.BeginHorizontal();
        if (GUILayout.Button("数组-添加字符串数组"))
        {
            ArrayTest tester = new ArrayTest();
            content1 = "Array : " + tester.addStrToStrArray();
            content2 = "ArrayList : " + tester.addStrToArrayList();
            content3 = "";
        }

        if (GUILayout.Button("数组-添加整型数组"))
        {
            ArrayTest tester = new ArrayTest();
            content1 = "Array : " + tester.addStrToStrArray();
            content2 = "ArrayList : " + tester.addStrToArrayList();
            content3 = "";
        }

        GUILayout.EndHorizontal();

        System.Action <ISorter <int> > sort = (ISorter <int> sorter) =>
        {
            CodeTimeTester timer = new CodeTimeTester();
            List <int>     list  = CodeTester.GetRandomIntList(10);
            content1 = "";
            list.ForEach(i => { content1 += i + " "; });

            timer.StartTime();
            sorter.Sort(list);
            timer.StopTime();

            content2 = getIntListContent(list);
            content3 = "耗时: " + timer.duration;
        };

        if (GUILayout.Button("冒泡排序"))
        {
            BubbleSort <int> sorter = new BubbleSort <int>();
            sort(sorter);
        }

        if (GUILayout.Button("快速排序"))
        {
            QuickSort <int> sorter = new QuickSort <int>();
            sort(sorter);
        }

        if (GUILayout.Button("选择排序"))
        {
            SelectionSort <int> sorter = new SelectionSort <int>();
            sort(sorter);
        }

        if (GUILayout.Button("插入排序"))
        {
            InsertionSort <int> sorter = new InsertionSort <int>();
            sort(sorter);
        }

        if (GUILayout.Button("希尔排序"))
        {
            ShellSort <int> sorter = new ShellSort <int>();
            sort(sorter);
        }

        if (GUILayout.Button("归并排序"))
        {
            MergeSort <int> sorter = new MergeSort <int>();
            sort(sorter);
        }

        if (GUILayout.Button("基数排序"))
        {
            RadixSort <int> sorter = new RadixSort <int>();
            sort(sorter);
        }

        if (GUILayout.Button("Stack - (5+6+3)"))
        {
            StackTest stack = new StackTest();
            content1 = stack.Test();
        }

        if (GUILayout.Button("Stack - 进制转换"))
        {
            StackTest stack = new StackTest();
            content1 = stack.MulBaseTest();
        }


        if (GUILayout.Button("BitArray - 素数"))
        {
            List <int> list = new List <int>();
            for (int i = 0; i < 100; ++i)
            {
                list.Add(1);
            }

            BitArrayTest bat = new BitArrayTest();

            content1 = bat.GetPrimes(list.ToArray());
        }


        scrollPos = GUILayout.BeginScrollView(scrollPos);
        GUILayout.Label(content1);
        GUILayout.Label(content2);
        GUILayout.Label(content3);
        GUILayout.EndScrollView();
    }
Beispiel #19
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();
        }
        private async void Button_Click(object sender, RoutedEventArgs e)
        {
            Button    clickedButton = (Button)sender;
            Stopwatch sw            = new Stopwatch();

            switch (clickedButton.Name.ToLower())
            {
            case "quick":
                break;

            case "insertion":
                iStatus.Text         = RUNNING;
                iSortRuntime.Content = string.Empty;
                sw.Start();
                await InsertionSort.SortAsync(RandomArray.GetRandomArray(DatasetSize, 0, 100), _cts);

                sw.Stop();
                iStatus.Text         = COMPLETE;
                iSortRuntime.Content = sw.Elapsed;
                break;

            case "evenodd":
                eoStatus.Text         = RUNNING;
                eoSortRuntime.Content = string.Empty;
                sw.Start();
                await EvenOddSort.SortAsync(RandomArray.GetRandomArray(DatasetSize, 0, 100), _cts);

                sw.Stop();
                eoStatus.Text         = COMPLETE;
                eoSortRuntime.Content = sw.Elapsed;
                break;

            case "arrayadd":
                arrayAddStatus.Text     = RUNNING;
                arrayAddRuntime.Content = string.Empty;
                sw.Start();
                await ArrayAddition.AddArraysAsync(RandomArray.GetRandomArray(DatasetSize, 0, 100),
                                                   RandomArray.GetRandomArray(DatasetSize, 0, 100), _cts);

                sw.Stop();
                arrayAddStatus.Text     = COMPLETE;
                arrayAddRuntime.Content = sw.Elapsed;
                break;

            case "arraysum":
                arraySumStatus.Text     = RUNNING;
                arraySumRuntime.Content = string.Empty;
                sw.Start();
                await ArraySum.SumAsync(RandomArray.GetRandomArray(DatasetSize, 0, 100), _cts);

                sw.Stop();
                arraySumStatus.Text     = COMPLETE;
                arraySumRuntime.Content = sw.Elapsed;
                break;

            case "parrayadd":
                pArrayAddStatus.Text     = RUNNING;
                pArrayAddRuntime.Content = string.Empty;
                sw.Start();
                await ParallelArrayAddition.AddArraysAsync(RandomArray.GetRandomArray(DatasetSize, 0, 100),
                                                           RandomArray.GetRandomArray(DatasetSize, 0, 100), _cts);

                sw.Stop();
                pArrayAddStatus.Text     = COMPLETE;
                pArrayAddRuntime.Content = sw.Elapsed;
                break;

            case "psum":
                pSumStatus.Text     = RUNNING;
                pSumRuntime.Content = string.Empty;
                sw.Start();
                await ParallelSum.SumAsync(RandomArray.GetRandomArray(DatasetSize, 0, 100), _cts);

                sw.Stop();
                pSumStatus.Text     = COMPLETE;
                pSumRuntime.Content = sw.Elapsed;
                break;

            case "reduct":
                reductStatus.Text     = RUNNING;
                reductRuntime.Content = string.Empty;
                sw.Start();
                await ReductionSum.SumAsync(RandomArray.GetRandomArray(DatasetSize, 0, 100));

                sw.Stop();
                reductStatus.Text     = COMPLETE;
                reductRuntime.Content = sw.Elapsed;
                break;

            case "all":
                iSortRuntime.Content     = string.Empty;
                eoSortRuntime.Content    = string.Empty;
                arrayAddRuntime.Content  = string.Empty;
                arraySumRuntime.Content  = string.Empty;
                pArrayAddRuntime.Content = string.Empty;
                pSumRuntime.Content      = string.Empty;
                allRuntime.Content       = string.Empty;
                iStatus.Text             = RUNNING;
                eoStatus.Text            = RUNNING;
                arrayAddStatus.Text      = RUNNING;
                arraySumStatus.Text      = RUNNING;
                pArrayAddStatus.Text     = RUNNING;
                pSumStatus.Text          = RUNNING;
                allStatus.Text           = RUNNING;
                sw.Start();
                Task inSort = InsertionSort.SortAsync(RandomArray.GetRandomArray(DatasetSize, 0, 100), _cts);
                Task eoSort = EvenOddSort.SortAsync(RandomArray.GetRandomArray(DatasetSize, 0, 100), _cts);
                Task arrAdd = ArrayAddition.AddArraysAsync(RandomArray.GetRandomArray(DatasetSize, 0, 100),
                                                           RandomArray.GetRandomArray(DatasetSize, 0, 100), _cts);
                Task arrSum = ArraySum.SumAsync(RandomArray.GetRandomArray(DatasetSize, 0, 100), _cts);
                Task parAdd = ParallelArrayAddition.AddArraysAsync(RandomArray.GetRandomArray(DatasetSize, 0, 100),
                                                                   RandomArray.GetRandomArray(DatasetSize, 0, 100), _cts);
                Task parSum = ParallelSum.SumAsync(RandomArray.GetRandomArray(DatasetSize, 0, 100), _cts);
                await inSort.ContinueWith(t =>
                {
                    this.Dispatcher.Invoke(() =>
                    {
                        iStatus.Text = COMPLETE;
                    });
                });

                await eoSort.ContinueWith(t =>
                {
                    this.Dispatcher.Invoke(() =>
                    {
                        eoStatus.Text = COMPLETE;
                    });
                });

                await arrAdd.ContinueWith(t =>
                {
                    this.Dispatcher.Invoke(() =>
                    {
                        arrayAddStatus.Text = COMPLETE;
                    });
                });

                await arrSum.ContinueWith(t =>
                {
                    this.Dispatcher.Invoke(() =>
                    {
                        arraySumStatus.Text = COMPLETE;
                    });
                });

                await parAdd.ContinueWith(t =>
                {
                    this.Dispatcher.Invoke(() =>
                    {
                        pArrayAddStatus.Text = COMPLETE;
                    });
                });

                await parSum.ContinueWith(t =>
                {
                    this.Dispatcher.Invoke(() =>
                    {
                        pSumStatus.Text = COMPLETE;
                    });
                });

                await Task.WhenAll(inSort, eoSort);

                sw.Stop();
                allRuntime.Content = sw.Elapsed;
                allStatus.Text     = COMPLETE;
                break;

            case "cancel":
                _cts?.Cancel();
                _cts = new CancellationTokenSource();
                break;

            default:
                break;
            }
        }
Beispiel #21
0
 public void Given_UnsortedArray_Expected_SortedArray(int[] d, int[] e)
 {
     int[] a = InsertionSort.Sort(d);
     Assert.True(Enumerable.SequenceEqual(e, a), "Actual: " + PrintArray(a));
 }
        public void IniziatizateExperiment()
        {
            string[] files = Directory.GetFiles(@"Data\Arrays\");
            Console.Write(Directory.GetCurrentDirectory());
            int[] algorithmType = new int[] {
                (int)AlgorithmType.BubbleSort,
                (int)AlgorithmType.InsertionSort,
            };
            string[] guid   = Guid.NewGuid().ToString().Split('-');
            string   id     = guid[0];
            var      myfile = File.Create(Directory.GetCurrentDirectory() + @"\Data\" + id + ".csv");

            myfile.Close();
            //StreamWriter streamWriter = new StreamWriter(Directory.GetCurrentDirectory() + @"\Data\" + id + ".csv");
            var csv = new StringBuilder();

            string header = "Processor,Array Size,Order Type, Algorithm, time, Executed Lines";

            csv.AppendLine(header);

            foreach (var file in files)
            {
                try
                {
                    StreamReader streamReader = new StreamReader(file);
                    string       line         = streamReader.ReadLine();

                    string[] numbers    = line.Split(' ');
                    int[]    intNumbers = Array.ConvertAll(numbers, int.Parse);

                    string[] info = file.Split('-');

                    string size       = info[0].Substring(11);
                    string orderType  = info[1].Last().ToString();
                    string proccessor = Processor;
                    string lineNumbers;
                    string time;

                    foreach (var algorithm in algorithmType)
                    {
                        if (algorithm == 0)
                        {
                            for (int i = 0; i < 10; i++)
                            {
                                int lines = BubbleSort.LinesBurbleSort(intNumbers);
                                lineNumbers = lines.ToString();
                                long intTime = BubbleSort.TimeBurbleSort(intNumbers);
                                time = intTime.ToString();
                                csv.AppendLine(proccessor + "," + size + "," + orderType + "," + algorithm + "," + time + "," + lineNumbers);
                                File.WriteAllText(Directory.GetCurrentDirectory() + @"\Data\" + id + ".csv", csv.ToString());
                            }
                        }
                        else
                        {
                            for (int i = 0; i < 10; i++)
                            {
                                int lines = InsertionSort.LinesInsertionSort(intNumbers);
                                lineNumbers = lines.ToString();
                                long intTime = InsertionSort.OrdenarInsertionSort(intNumbers);
                                time = intTime.ToString();
                                csv.AppendLine(proccessor + "," + size + "," + orderType + "," + algorithm + "," + time + "," + lineNumbers);
                                File.WriteAllText(Directory.GetCurrentDirectory() + @"\Data\" + id + ".csv", csv.ToString());
                            }
                        }
                    }
                    streamReader.Close();
                }
                catch (Exception)
                {
                    throw;
                }
            }
            File.WriteAllText(Directory.GetCurrentDirectory() + @"\Data\" + id + ".csv", csv.ToString());
            Console.WriteLine("End");
        }
Beispiel #23
0
 public void InsertionSort_GivenArrayOfOneElement_ReturnsArray()
 {
     int[] expected = new int[] { 1 };
     int[] actual   = InsertionSort.Sort(expected);
     Assert.Equal(expected, actual);
 }
Beispiel #24
0
        public void InsertionSort_SortData_and_Assert(int[] inputArray, int[] expectedArray)
        {
            var outputArray = InsertionSort.Sort(inputArray);

            Assert.Equal(expectedArray, outputArray);
        }
 //This will show how the num list runs on each algorithm
 //This allows the user to compare them
 public void hitSpeedCompButton()
 {
     algView = !algView;            //Change whether you are looking at the algorithm or speed comparison
     if (algView)                   //If you are now viewing at the algorithm pseudocode
     {
         algText.text = oldAlgText; //Change the text back to the pseudocode
         if (!half)
         {
             algDescription.enabled = true;
         }
         speedCompText.text = "Speed Comparison";
     }
     else//Otherwise display the speed comparison
     {
         oldAlgText = algText.text;
         string storageText = "Bubble Sort:{0} μs\nCocktail Sort: {1} μs\nComb Sort: {2} μs\nHeap Sort: {3}" +
                              " μs\nInsertion Sort: {4} μs\nMerge Sort:{5} μs\nQuick Sort:{6} μs\nShell Sort:{7} μs\nFlash Sort:{8} μs" +
                              "\nBucket Sort:{9} μs\nRadix Sort:{10} μs";
         //Format the text to show each element in microseconds
         algText.text = string.Format(storageText, BubbleSort.BubbleSortTime(new List <int>(copy)),
                                      CocktailSort.CocktailSortTime(new List <int>(copy)), CombSort.CombSortTime(new List <int>(copy)),
                                      HeapSort.HeapSortStartTime(new List <int>(copy)), InsertionSort.InsertionSortTime(new List <int>(copy)),
                                      Mergesort.MergeSortTime(new List <int>(copy), 0, copy.Count - 1), QuickSort.QuickSortStartTime(new List <int>(copy), 0, copy.Count - 1),
                                      ShellSort.ShellSortTime(new List <int>(copy)), FlashSort.FlashSortTime(new List <int>(copy)), BucketSort.BucketSortTime(new List <int>(copy), 34)
                                      , RadixSort.RadixSortTime(new List <int>(copy)));
         algDescription.enabled = false;
         speedCompText.text     = "Algorithm";
     }
 }
Beispiel #26
0
 public void Should_Order_Worst_Case()
 {
     int [] inputArray  = { 6, 5, 4, 3, 2, 1 };
     int [] outputArray = { 1, 2, 3, 4, 5, 6 };
     Assert.Equal(InsertionSort.Sort(inputArray), outputArray);
 }
Beispiel #27
0
        public void DisplayArrayAndString()
        {
            Console.WriteLine("Select Question[1-10]");
            int choice = int.Parse(Console.ReadLine());

            switch (choice)
            {
                #region Max Sub Array Sum Using Kadens Algo
            case 1:
                Console.WriteLine("--------" + choice + ".Max Sub Array Sum Using Kadens Algo--------");
                FindMaxSubArraySumUsingKadensAlgo o1 = new FindMaxSubArraySumUsingKadensAlgo();
                int[] arr1 = { 2, -1, -3, 4, -1, 7, -2 };
                Console.WriteLine(o1.MaxSub(arr1));
                break;
                #endregion

                #region Binary Search
            case 2:
                Console.WriteLine("--------" + choice + ".Binary Search--------");
                BinarySearch o2   = new BinarySearch();
                int[]        arr2 = { 5, 10, 20, 30, 40 };
                Console.WriteLine(o2.BSEarch(arr2, 0, arr2.Length - 1, 40));
                break;
                #endregion

                #region Check Palindrome
            case 3:
                Console.WriteLine("--------" + choice + ".Check Palindrome--------");
                StringPalindrome o3 = new StringPalindrome();
                Console.WriteLine("Enter a String to check Palindrome or not");
                string str3 = Console.ReadLine();
                Console.WriteLine($"{str3} is palindrome {o3.CheckPalindrome(str3)}");
                break;
                #endregion

                #region Bubble Sort
            case 4:
                Console.WriteLine("--------" + choice + ".Bubble Sort--------");
                int[]      arr = { 1, 2, 3, 4 };
                BubbleSort o4  = new BubbleSort(arr, arr.Length);
                break;
                #endregion

                #region Insertion Sort
            case 5:
                Console.WriteLine("--------" + choice + ".Insertion Sort--------");
                var o5 = new InsertionSort(new int[] { 8, 4, 1, 5 });
                break;
                #endregion

                #region Selection sort
            case 6:
                Console.WriteLine("--------" + choice + ".Selection Sort--------");
                var o6 = new SelectionSort(new int[] { 4, 6, 9, 2, 3, 1 });
                break;
                #endregion

                #region Quick Sort
            case 7:
                Console.WriteLine("--------" + choice + ".Quick Sort--------");
                var o7 = new SelectionSort(new int[] { 4, 6, 9, 2, 3, 1 });
                break;
                #endregion

                #region Merge Sort
            case 8:
                Console.WriteLine("--------" + choice + ".Merge Sort--------");
                var o8 = new MergeSort(new int[] { 4, 6, 9, 2, 3, 1 });
                break;
                #endregion

                #region
            case 9:
                Console.WriteLine("--------" + choice + ".String Reverse--------");
                Console.WriteLine($"Test the String Reverse! : { ReverseString.Reverse("Test the String Reverse!")}");
                break;
                #endregion

                #region
            case 10:
                Console.WriteLine("--------" + choice + ".--------");

                break;
                #endregion

            default:
                Console.WriteLine("Oops! Inavalid Choice.");
                break;
            }
        }
Beispiel #28
0
 public int[] InsertionSortReturnsSortedArray(int[] arr) => InsertionSort.Sort(arr);
Beispiel #29
0
 public void SortTest()
 {
     Assert.IsTrue(InsertionSort.Sort(new[] { 5, 7, 7, -5, 0, 1, 14, -11 })
                   .SequenceEqual(new[] { -11, -5, 0, 1, 5, 7, 7, 14 }));
 }
Beispiel #30
0
        static void Main(string[] args)
        {
            //Read CSV
            List <int> numbers = CSVReader.ReadCSV(@"H:\Other\Uni\Diploma\Semester 1\Programming\Week 14 - NeedToComplete\unsorted_numbers.csv");

            //Timer
            DateTime start;
            DateTime end;

            //SORTING

            //Insert
            start = System.DateTime.Now;
            List <int> insertionSorted = InsertionSort.Sort(numbers);

            end = System.DateTime.Now;
            TimeSpan insertionTime = end - start;

            //Shell
            start = System.DateTime.Now;
            List <int> shellSorted = ShellSort.Sort(numbers);

            end = System.DateTime.Now;
            TimeSpan shellTime = end - start;

            //Times
            Console.WriteLine("Sorting times:");
            Console.WriteLine($"Insertion sorted in: { insertionTime.TotalSeconds} seconds");
            Console.WriteLine($"Shell sorted in: { shellTime.TotalSeconds} seconds");

            //SEARCHING

            //Numbers to Search
            int[] numSearch = new int[]
            {
                insertionSorted[0],
                insertionSorted[1500],
                insertionSorted[3000],
                insertionSorted[4500],
                insertionSorted[6000],
                insertionSorted[7500],
                insertionSorted[9000],
                insertionSorted[10500],
                insertionSorted[12000],
                insertionSorted[13500],
                insertionSorted.Last(),
            };

            //Linear
            Console.WriteLine("\nLinear searching:");
            start = System.DateTime.Now;
            foreach (int number in numSearch)
            {
                int?LinearPosition = LinearSearch.Search(insertionSorted, number);
                Console.WriteLine($"number {number} found at position {LinearPosition}");
            }
            end = System.DateTime.Now;
            TimeSpan linearSortedTime = end - start;

            Console.WriteLine($"Linear search time in seconds: {linearSortedTime.TotalSeconds}");

            //Binary
            Console.WriteLine("\nBinary searching:");
            start = System.DateTime.Now;
            foreach (int number in numSearch)
            {
                int?BinaryPosition = Binary.Search(insertionSorted, number);
                Console.WriteLine($"number {number} found at position {BinaryPosition}");
            }
            end = System.DateTime.Now;
            TimeSpan binaryTime = end - start;

            Console.WriteLine($"Binary search time seconds: {binaryTime.TotalSeconds}");
        }
Beispiel #31
0
 public void Test_InsertionSort()
 {
     //InsertionSort.SortIterative(arr);
     InsertionSort.SortRecursive(arr, arr.Length);
 }
 /// <summary>
 /// Default constructor.
 /// Initializes all class-wide test-dependent members.
 /// </summary>
 public InsertionSortTests()
 {
     this.testDriver    = new TestEngine(TEST_BREADTH, TEST_DEPTH);
     this.insertionSort = new InsertionSort();
 }
 public override void Configure()
 {
     _algorithm = new InsertionSort();
 }
Beispiel #34
0
 public void InsertionSort_GivenEmptyArray_ReturnsArray()
 {
     int[] expected = new int[0];
     int[] actual   = InsertionSort.Sort(expected);
     Assert.Equal(expected, actual);
 }
Beispiel #35
0
    public override IEnumerator Demo(GameObject[] sortingElements)
    {
        i = 0;
        j = 0;

        // Line 0 (set parameter)
        pseudoCodeViewer.SetCodeLine(CollectLine(0), Util.BLACKBOARD_TEXT_COLOR);

        // Create buckets
        Vector3[] pos = new Vector3[1] {
            bucketManager.FirstBucketPosition
        };
        int numberOfBuckets = bucketSortManager.NumberOfBuckets;

        bucketManager.CreateObjects(numberOfBuckets, pos);

        // Line 1 (Create buckets)
        yield return(HighlightPseudoCode(CollectLine(1), Util.HIGHLIGHT_STANDARD_COLOR));

        // Buckets
        GameObject[] buckets = null;
        if (bucketManager != null)
        {
            buckets = bucketManager.Buckets;
        }

        // Add elements to buckets
        for (i = 0; i < sortingElements.Length; i++)
        {
            // Check if user wants to stop the demo
            if (sortMain.UserStoppedTask)
            {
                break;
            }

            // Line 2 (Update for-loop)
            yield return(HighlightPseudoCode(CollectLine(2), Util.HIGHLIGHT_STANDARD_COLOR));

            // Check if user wants to stop the demo
            if (sortMain.UserStoppedTask)
            {
                break;
            }

            // Get element
            GameObject element = sortingElements[i];
            PreparePseudocodeValue(element.GetComponent <SortingElementBase>().Value, 1);

            // Bucket index
            bucketIndex = BucketIndex(value1, numberOfBuckets, maxValue);

            // Line 3 (Display bucket index)
            yield return(HighlightPseudoCode(CollectLine(3), Util.HIGHLIGHT_STANDARD_COLOR));

            // Check if user wants to stop the demo
            if (sortMain.UserStoppedTask)
            {
                break;
            }

            // Get bucket
            Bucket bucket = buckets[bucketIndex].GetComponent <Bucket>(); // element.GetComponent<SortingElementBase>().Value - minValue);

            // Move element above the bucket and put it inside
            element.transform.position = bucket.transform.position + UtilSort.ABOVE_BUCKET_VR;

            // Line 4 (Put element into bucket)
            yield return(HighlightPseudoCode(CollectLine(4), Util.HIGHLIGHT_STANDARD_COLOR));
        }

        // Line 5 (end for-loop)
        yield return(HighlightPseudoCode(CollectLine(5), Util.HIGHLIGHT_STANDARD_COLOR));

        // Display elements
        for (int x = 0; x < numberOfBuckets; x++)
        {
            // Check if user wants to stop the demo
            if (sortMain.UserStoppedTask)
            {
                break;
            }

            // Line 6 (For-loop: Sort elements in buckets)
            //pseudoCodeViewer.SetCodeLine(6, PseudoCode(6, x, Util.NO_VALUE, Util.NO_VALUE, true), Util.HIGHLIGHT_COLOR);
            //yield return new WaitForSeconds(seconds);
            //pseudoCodeViewer.SetCodeLine(6, PseudoCode(6, x, Util.NO_VALUE, Util.NO_VALUE, true), Util.BLACKBOARD_TEXT_COLOR);

            Bucket bucket = buckets[x].GetComponent <Bucket>();
            bucket.SetEnterTrigger(false);

            // Sort bucket *** TODO: go to insertion sort scene
            bucket.CurrenHolding = InsertionSort.InsertionSortStandard2(bucket.CurrenHolding);

            // Line 6 (Sort elements in bucket)
            i = x;
            yield return(HighlightPseudoCode(CollectLine(6), Util.HIGHLIGHT_STANDARD_COLOR));

            // Check if user wants to stop the demo
            if (sortMain.UserStoppedTask)
            {
                break;
            }

            // Put elements for display on top of buckets
            int numberOfElementsInBucket = bucket.CurrenHolding.Count;
            for (int y = 0; y < numberOfElementsInBucket; y++)
            {
                // Check if user wants to stop the demo
                if (sortMain.UserStoppedTask)
                {
                    break;
                }

                SortingElementBase element = bucket.GetElementForDisplay(y);
                element.gameObject.active   = true;
                element.transform.position += UtilSort.ABOVE_BUCKET_VR;
                yield return(demoStepDuration);
            }
        }
        // Line 8 (end for loop)
        //pseudoCodeViewer.SetCodeLine(8, PseudoCode(8, Util.NO_VALUE, Util.NO_VALUE, Util.NO_VALUE, true), Util.HIGHLIGHT_COLOR);
        //yield return new WaitForSeconds(seconds);
        //pseudoCodeViewer.SetCodeLine(8, PseudoCode(8, Util.NO_VALUE, Util.NO_VALUE, Util.NO_VALUE, true), Util.BLACKBOARD_TEXT_COLOR);

        // Put elements back into list
        k = 0;
        // Line 7 (set k)
        yield return(HighlightPseudoCode(CollectLine(7), Util.HIGHLIGHT_STANDARD_COLOR));

        // Holder positions (where the sorting elements initialized)
        Vector3[] holderPos = sortMain.HolderManager.GetHolderPositions();
        // while (k < sortingElements.Length && i < numberOfBuckets)
        for (i = 0; i < numberOfBuckets; i++)
        {
            // Check if user wants to stop the demo
            if (sortMain.UserStoppedTask)
            {
                break;
            }

            Bucket bucket = buckets[i].GetComponent <Bucket>();

            // number of elements in bucket
            bucketSize = bucket.CurrenHolding.Count.ToString();

            // Line 8 (For-loop: Concatenate all buckets)
            yield return(HighlightPseudoCode(CollectLine(8), Util.HIGHLIGHT_STANDARD_COLOR));

            for (j = 0; j < bucket.CurrenHolding.Count; j++)
            {
                // Check if user wants to stop the demo
                if (sortMain.UserStoppedTask)
                {
                    break;
                }

                // Line 9 (2nd For-loop: Concatenate all buckets)
                yield return(HighlightPseudoCode(CollectLine(9), Util.HIGHLIGHT_STANDARD_COLOR));

                // Check if user wants to stop the demo
                if (sortMain.UserStoppedTask)
                {
                    break;
                }

                sortingElements[k] = bucket.RemoveSoringElement().gameObject;

                // Value of sorting element
                PreparePseudocodeValue(sortingElements[k].GetComponent <SortingElementBase>().Value, 2);

                // Move element back to holder
                sortingElements[k].transform.position = holderPos[k] + UtilSort.ABOVE_HOLDER_VR;
                sortingElements[k].transform.rotation = Quaternion.identity;
                sortingElements[k].GetComponent <SortingElementBase>().IsSorted = true;

                // Line 10 (Put element back into list)
                yield return(HighlightPseudoCode(CollectLine(10), Util.HIGHLIGHT_STANDARD_COLOR));

                // Check if user wants to stop the demo
                if (sortMain.UserStoppedTask)
                {
                    break;
                }

                // Line 11 (Update k)
                yield return(HighlightPseudoCode(CollectLine(11), Util.HIGHLIGHT_STANDARD_COLOR));

                k++;
            }
            // Line 12 (2nd for-inner-loop end)
            yield return(HighlightPseudoCode(CollectLine(12), Util.HIGHLIGHT_STANDARD_COLOR));

            // Check if user wants to stop the demo
            if (sortMain.UserStoppedTask)
            {
                break;
            }
        }
        // Line 13 (2nd for-loop end)
        yield return(HighlightPseudoCode(CollectLine(13), Util.HIGHLIGHT_STANDARD_COLOR));


        if (sortMain.UserStoppedTask)
        {
            sortMain.UpdateCheckList(Util.DEMO, true);
        }
        else
        {
            isTaskCompleted = true;
        }
    }
Beispiel #36
0
 static void Main(string[] args)
 {
     InsertionSort.Sort(new int[] { 5, 4, 3, 2, 1 });
     Console.WriteLine("Hello World!");
 }
Beispiel #37
0
    public override Dictionary <int, InstructionBase> UserTestInstructions(InstructionBase[] sortingElements)
    {
        Dictionary <int, InstructionBase> instructions = new Dictionary <int, InstructionBase>();
        int instNr = 0;

        // Line 0 (set parameter)
        instructions.Add(instNr, new InstructionBase(Util.FIRST_INSTRUCTION, instNr++));

        // Create buckets
        Vector3[] pos = new Vector3[1] {
            bucketManager.FirstBucketPosition
        };
        int numberOfBuckets = bucketSortManager.NumberOfBuckets;

        bucketManager.CreateObjects(numberOfBuckets, pos);

        // Line 1 (Create buckets)
        instructions.Add(instNr, new InstructionBase(UtilSort.CREATE_BUCKETS_INST, instNr++));

        int x;

        // Add elements to buckets
        for (x = 0; x < sortingElements.Length; x++)
        {
            // Line 2 (Update for-loop)
            instructions.Add(instNr, new InstructionLoop(UtilSort.FIRST_LOOP, instNr++, x, Util.NO_VALUE, Util.NO_VALUE)); // TODO: create one unique instruction for each loop

            // Get element
            BucketSortInstruction element = (BucketSortInstruction)sortingElements[x];
            int bucketIndex = BucketIndex(element.Value, numberOfBuckets, maxValue);

            // Line 3 (Display bucket index)
            instructions.Add(instNr, new BucketSortInstruction(UtilSort.BUCKET_INDEX_INST, instNr++, x, Util.NO_VALUE, Util.NO_VALUE, element.SortingElementID, element.Value, true, false, element.HolderID, UtilSort.NO_DESTINATION, bucketIndex));

            // Line 4 (Put element into bucket)
            instructions.Add(instNr, new BucketSortInstruction(UtilSort.MOVE_TO_BUCKET_INST, instNr++, x, Util.NO_VALUE, Util.NO_VALUE, element.SortingElementID, element.Value, false, false, element.HolderID, UtilSort.NO_DESTINATION, bucketIndex));
        }
        // Line 2: condition
        instructions.Add(instNr, new InstructionLoop(UtilSort.FIRST_LOOP, instNr++, x, Util.NO_VALUE, Util.NO_VALUE));

        // Line 5 (end for-loop)
        instructions.Add(instNr, new InstructionLoop(UtilSort.END_LOOP_INST, instNr++, Util.NO_VALUE, Util.NO_VALUE, Util.NO_VALUE, UtilSort.OUTER_LOOP));

        // Line 6 (make the buckets sort what they hold)
        instructions.Add(instNr, new InstructionBase(UtilSort.PHASING_INST, instNr++));

        // Sorting elements
        int[] values = new int[sortingElements.Length];
        for (int y = 0; y < sortingElements.Length; y++)
        {
            values[y] = ((BucketSortInstruction)sortingElements[y]).Value;
        }
        int[] sorted = InsertionSort.InsertionSortFixCase(values, false);

        // Creating fictionary buckets
        Dictionary <int, List <BucketSortInstruction> > buckets = new Dictionary <int, List <BucketSortInstruction> >();

        for (int y = 0; y < numberOfBuckets; y++)
        {
            buckets[y] = new List <BucketSortInstruction>();
        }

        // Look for correct value and add element to bucket
        for (int r = 0; r < sorted.Length; r++)
        {
            for (int s = 0; s < sortingElements.Length; s++)
            {
                BucketSortInstruction t = (BucketSortInstruction)sortingElements[s];
                if (sorted[r] == t.Value)
                {
                    int bucketIndex = BucketIndex(t.Value, bucketSortManager.NumberOfBuckets, maxValue);
                    BucketSortInstruction displayInstruction = new BucketSortInstruction(UtilSort.DISPLAY_ELEMENT, instNr, Util.NO_VALUE, Util.NO_VALUE, Util.NO_VALUE, t.SortingElementID, t.Value, false, true, Util.NO_VALUE, UtilSort.NO_DESTINATION, bucketIndex);
                    instructions.Add(instNr++, displayInstruction);
                    buckets[bucketIndex].Add(displayInstruction);
                    break;
                }
            }
        }

        int i, j, k = 0;

        // Line 7 (For-loop: Concatenate all buckets)
        instructions.Add(instNr, new InstructionBase(Util.SET_VAR_K, instNr++));

        // Holder positions (where the sorting elements initialized)
        Vector3[] holderPos = sortMain.HolderManager.GetHolderPositions();
        for (i = 0; i < numberOfBuckets; i++)
        {
            List <BucketSortInstruction> bucket = buckets[i];
            int numberOfElementsInBucket        = bucket.Count;

            // Line 8 (For-loop: Concatenate all buckets)
            instructions.Add(instNr, new InstructionLoop(UtilSort.UPDATE_LOOP_INST, instNr++, i, numberOfBuckets, k, UtilSort.OUTER_LOOP));

            for (j = 0; j < numberOfElementsInBucket; j++)
            {
                // Line 9 (2nd For-loop: Concatenate all buckets)
                instructions.Add(instNr, new InstructionLoop(UtilSort.UPDATE_LOOP_INST, instNr++, i, j, numberOfElementsInBucket, UtilSort.INNER_LOOP));

                // Line 10 (Put element back into list)
                instructions.Add(instNr, new BucketSortInstruction(UtilSort.MOVE_BACK_INST, instNr++, i, j, k, bucket[j].SortingElementID, bucket[j].Value, false, true, Util.NO_VALUE, k, bucket[j].BucketID));

                // Line 11 (Update k)
                instructions.Add(instNr, new InstructionLoop(Util.UPDATE_VAR_K, instNr++, i, j, k));
                k++;
            }
            // Line 9: condition
            instructions.Add(instNr, new InstructionLoop(UtilSort.UPDATE_LOOP_INST, instNr++, i, j, numberOfElementsInBucket, UtilSort.INNER_LOOP));
            // Line 12 (2nd for-loop end)
            instructions.Add(instNr, new InstructionLoop(UtilSort.END_LOOP_INST, instNr++, i, Util.NO_VALUE, k, UtilSort.INNER_LOOP));
        }
        // Line 8: condition
        instructions.Add(instNr, new InstructionLoop(UtilSort.UPDATE_LOOP_INST, instNr++, i, numberOfBuckets, k, UtilSort.OUTER_LOOP));
        // Line 13 (2nd for-loop end)
        instructions.Add(instNr, new InstructionBase(Util.FINAL_INSTRUCTION, instNr++));

        return(instructions);
    }