예제 #1
0
        static void Main(string[] args)
        {
            int[] arrayOfInts = { 36, 35, 40, 39, 30,  5, 14, 13, 16, 17, 18, 20, 83, 84, 24, 28, 27, 26, 10, 90, 89, 78, 67, 48, 68, 97,
                                  56, 45, 43, 31, 22, 94, 34, 43, 56, 37, 98, 58, 98, 87, 84, 81, 71, 51, 50, 42, 49, 47, 75, 91,
                                  64, 63, 08, 84, 86, 88, 31, 51, 76, 87, 95, 92, 66, 55, 44, 33, 22, 11, 88, 99, 80, 60, 59, 82,
                                  4,   6,  7,  2, 31, 51, 62, 21, 32, 25, 21, 29, 99, 94, 76, 54, 84, 03, 45, 69, 87, 22, 85, 53, 73,
                                  11,  1, 23, 45, 12, 34, 67, 34, 89, 77, 16, 01, 38, 90, 56, 65, 33, 17, 19,  2,  9, 87, 88, 57, 74,
                                  54, 93, 96, 52, 77,  6, 89, 32, 54, 89, 44, 46, 41, 76, 72, 70, 86, 84, 31, 07, 61, 67, 63 };

            int[] bubbleSortInputArray = arrayOfInts.Clone() as int[];

            Stopwatch watchBubbleSort = DoSortIntegers(BubbleSort.SortIntegers, bubbleSortInputArray);

            Console.WriteLine("Sorted Array with Bubble Sort = {0} ", BuildOutputString(bubbleSortInputArray));
            Console.WriteLine("Time taken for Bubble Sort = {0} ", watchBubbleSort.ElapsedTicks);

            int[] selectionSortInputArray = arrayOfInts.Clone() as int[];

            Stopwatch watchSelectionSort = DoSortIntegers(SelectionSort.SortIntegers, selectionSortInputArray);

            Console.WriteLine("Sorted Array with Selection Sort = {0} ", BuildOutputString(selectionSortInputArray));
            Console.WriteLine("Time taken for Selection Sort = {0} ", watchSelectionSort.ElapsedTicks);

            int[] insertionSortInputArray = arrayOfInts.Clone() as int[];

            Stopwatch watchInsertionSort = DoSortIntegers(InsertionSort.SortIntegers, insertionSortInputArray);

            Console.WriteLine("Sorted Array with Insertion Sort = {0} ", BuildOutputString(insertionSortInputArray));
            Console.WriteLine("Time taken for Insertion Sort = {0} ", watchInsertionSort.ElapsedTicks);

            int[] quickSortInputArray = arrayOfInts.Clone() as int[];

            Stopwatch watchQuickSort = DoSortIntegers(QuickSort.SortIntegers, quickSortInputArray);

            Console.WriteLine("Sorted Array with Quick Sort = {0} ", BuildOutputString(quickSortInputArray));
            Console.WriteLine("Time taken for Quick Sort = {0} ", watchQuickSort.ElapsedTicks);

            //Disadvantage of Abstract factory. Since MergeSort.SortIntegers could not conform to the delegate signature
            //Could not use that and therefore has to have this implementation.
            int[]     mergeSortInputArray = arrayOfInts.Clone() as int[];
            Stopwatch watch = new Stopwatch();

            watch.Start();
            int[] mergeSortedArray = MergeSort.SortIntegers(mergeSortInputArray);
            watch.Stop();

            Console.WriteLine("Sorted Array with Merge Sort = {0} ", BuildOutputString(mergeSortedArray));
            Console.WriteLine("Time taken for Merge Sort = {0} ", watch.ElapsedTicks);

            Console.ReadKey();
        }
예제 #2
0
        static void Main(string[] args)
        {
            // -------------------- Bubble Sort --------------------
            var bubbleNumbers = new[] { 7, 3, 1, 4, 6, 2, 3 };
            var bubbleSorter  = new BubbleSort();

            bubbleSorter.Sort(bubbleNumbers);
            Console.WriteLine($"[{string.Join(", ", bubbleNumbers)}]");

            // -------------------- Selection Sort --------------------
            var selectionNumbers = new[] { 7, 3, 1, 4, 6, 2, 3 };
            var selectionSorter  = new SelectionSort();

            selectionSorter.Sort(selectionNumbers);
            Console.WriteLine("[{0}]", string.Join(", ", selectionNumbers));

            // -------------------- Insertion Sort --------------------
            var insertionNumbers = new[] { 7, 3, 1, 4, 6, 2, 3 };
            var insertionSorter  = new InsertionSort();

            insertionSorter.Sort(insertionNumbers);
            Console.WriteLine("[{0}]", string.Join(", ", insertionNumbers));

            // -------------------- Merge Sort --------------------
            int[] mergeNumbers = { 7, 3, 1, 4, 6, 2, 3 };
            var   mergeSorter  = new MergeSort();

            mergeSorter.Sort(mergeNumbers);
            Console.WriteLine("[{0}]", string.Join(", ", mergeNumbers));

            // -------------------- Quick Sort --------------------
            int[] quickNumbers = { 7, 3, 1, 4, 6, 2, 3 };
            var   quickSorter  = new QuickSort();

            quickSorter.Sort(quickNumbers);
            Console.WriteLine("[{0}]", string.Join(", ", quickNumbers));

            // -------------------- Counting Sort --------------------
            int[] countingNumbers = { 7, 3, 1, 4, 6, 2, 3 };
            var   countingSorter  = new CountingSort();

            countingSorter.Sort(countingNumbers);
            Console.WriteLine("[{0}]", string.Join(", ", countingNumbers));

            // -------------------- Bucket Sort --------------------
            int[] bucketNumbers = { 7, 3, 1, 4, 6, 2, 3 };
            var   bucketSorter  = new BucketSort();

            bucketSorter.Sort(bucketNumbers, 3);
            Console.WriteLine("[{0}]", string.Join(", ", bucketNumbers));
        }
        static void Main(string[] args)
        {
            var array         = new int[] { 6, 2, 9, 4, 5 };
            var bubbleSort    = new BubbleSort();
            var selectionSort = new SelectionSort();
            var insertionSort = new InsertionSort();
            var mergeSort     = new MergeSort();

            Console.WriteLine("NoSorted: " + string.Join(",", array));
            //bubbleSort.Sort(array);
            //selectionSort.Sort(array);
            //insertionSort.Sort(array);
            mergeSort.Sort(array);
            Console.WriteLine("Sorted: " + string.Join(",", array));
        }
예제 #4
0
        public void TryMergeSort()
        {
            MergeSort Merging = new MergeSort();

            for (int i = 0; i < notSorted.Length; i++)
            {
                int value = random.Next(1, 5000);
                notSorted[i] = value;
            }
            Merging.RecursiveMergeSort(notSorted, 0, notSorted.Length - 1);
            Console.WriteLine("==========Integer Array OutPut===============");
            for (int i = 0; i < notSorted.Length; i++)
            {
                Console.WriteLine(notSorted[i]);
            }
            Console.ReadKey();
        }
예제 #5
0
        static void Main(string[] args)
        {
            var rnd     = new Random();
            var arrSize = rnd.Next(1, 1000);

            int[] arr = Enumerable.Repeat(0, arrSize).Select(x => rnd.Next(int.MinValue, int.MaxValue)).ToArray();
            var   bs  = (int[])arr.Clone();

            BubbleSort.Sort(bs);
            Assert.IsTrue(IsSorted(bs));

            var ss = (int[])arr.Clone();

            SelectionSort.Sort(ss);
            Assert.IsTrue(IsSorted(ss));

            var @is = (int[])arr.Clone();

            InsertionSort.Sort(@is);
            Assert.IsTrue(IsSorted(@is));

            var ms = (int[])arr.Clone();

            MergeSort.Sort(ms);
            Assert.IsTrue(IsSorted(ms));

            var qs = (int[])arr.Clone();

            QuickSort.Sort(qs);
            Assert.IsTrue(IsSorted(qs));

            var cs = (int[])arr.Clone();

            CountingSort.Sort(cs);
            Assert.IsTrue(IsSorted(cs));

            var rs = (int[])arr.Clone();

            RadixSort.Sort(rs);
            Assert.IsTrue(IsSorted(rs));

            var hs = (int[])arr.Clone();

            HeapSort.Sort(hs);
            Assert.IsTrue(IsSorted(hs));
        }
예제 #6
0
        static void RunSorts()
        {
            var watch = new System.Diagnostics.Stopwatch();

            Console.WriteLine("Unsorted int array size of {0}", unsortedArray.Length);

            watch.Start();
            InsertionSort ISort = new InsertionSort(unsortedArray);

            watch.Stop();

            Console.WriteLine("Insertion Sort - Ticks/ Time in Milliseconds spent to create object and sort the array: " + watch.Elapsed.Ticks);
            watch.Reset();

            watch.Start();
            MergeSort MSort = new MergeSort(unsortedArray);

            watch.Stop();

            Console.WriteLine("Merge Sort - Ticks/ Time in Milliseconds spent to create object and sort the array: " + watch.Elapsed.Ticks);

            watch.Reset();

            watch.Start();
            QuickSort QSort = new QuickSort(unsortedArray);

            watch.Stop();

            Console.WriteLine("Quick Sort - Ticks/ Time in Milliseconds spent to create object and sort the array: " + watch.Elapsed.Ticks);



            watch.Reset();
            watch.Start();
            Array.Sort(unsortedArray);
            watch.Stop();

            //This method uses the Array.Sort method, which applies the introspective sort as follows:
            //•If the partition size is fewer than 16 elements, it uses an insertion sort algorithm.
            //•If the number of partitions exceeds 2 * LogN, where N is the range of the input array, it uses a Heapsort algorithm.
            //•Otherwise, it uses a Quicksort algorithm.

            Console.WriteLine(".Net Sort - Ticks/ Time in Milliseconds spent to create object and sort the array: " + watch.Elapsed.Ticks);
        }
예제 #7
0
        static void Main(string[] args)
        {
            RegisterDependencies();
            int[] unsortedNumbers;

            using (var scope = Container.BeginLifetimeScope())
            {
                _timerService = scope.Resolve <ITimerService>();

                unsortedNumbers = new int[] { 7, 2, 1, 6, 8, 5, 3, 4 };
                var heapSort = new HeapSort(_timerService);
                Sort(heapSort, unsortedNumbers);

                unsortedNumbers = new int[] { 7, 2, 1, 6, 8, 5, 3, 4 };
                var mergeSort = new MergeSort(_timerService);
                Sort(mergeSort, unsortedNumbers);

                unsortedNumbers = new int[] { 7, 2, 1, 6, 8, 5, 3, 4 };
                var quickSort = new QuickSort(_timerService);
                Sort(quickSort, unsortedNumbers);
            }
        }
예제 #8
0
        static void Main(string[] args)
        {
            int[] array = new int[] { 5, 10, 3, 2, 4, 3 };
            Console.Write("Bubble Sort: ");
            BubbleSort.sort(array);
            print(array);

            array = new int[] { 5, 10, 3, 2, 4, 3 };
            Console.Write("Insertion Sort: ");
            InsertionSort.sort(array);
            print(array);

            array = new int[] { 5, 10, 3, 2, 4, 3 };
            Console.Write("Selection Sort: ");
            SelectionSort.sort(array);
            print(array);

            array = new int[] { 5, 10, 3, 2, 4, 3 };
            Console.Write("Merge Sort: ");
            MergeSort.sort(array, 0, array.Length - 1);
            print(array);
        }
예제 #9
0
        public static void Sort(uint[] UnsortedArray, int Length, SortNames AlgorithmName)
        {
            ISort Algorithm = null;

            switch (AlgorithmName)
            {
            case (SortNames.SelectionSort):
                Algorithm = new SelectionSort();
                break;

            case (SortNames.InsertionSort):
                Algorithm = new InsertionSort();
                break;

            case (SortNames.ShellSort1):
                Algorithm = new ShellSort1();
                break;

            case (SortNames.ShellSort2):
                Algorithm = new ShellSort2();
                break;

            case (SortNames.QuickSort):
                Algorithm = new QuickSort();
                break;

            case (SortNames.MergeSort):
                Algorithm = new MergeSort();
                break;

            case (SortNames.RadixSort):
                Algorithm = new RadixSort();
                break;
            }
            Algorithm.Sort(UnsortedArray, Length);
        }
예제 #10
0
        private void MergeSortButton_Click(object sender, EventArgs e)
        {
            var merge = new MergeSort <SortedItem>(items);

            Button_Click(merge);
        }
예제 #11
0
        static void Main(string[] args)
        {
            Random random = new Random();

            Console.WriteLine("Enter the Number");

            int c = Console.Read();

            int[] arr = new int[c];

            for (int i = 0; i < c; i++)
            {
                arr[i] = random.Next();
            }


            Console.WriteLine("Choose The Algorhitm ");

            Console.WriteLine("1: InsertSort");

            Console.WriteLine("2: BubbleSort");

            Console.WriteLine("3: Quick Sort");

            Console.WriteLine("4: Heap Sort");

            Console.WriteLine("5: Merge Sort");

            Console.WriteLine("6: All");



            string s = Console.ReadLine();

            if (s.Length > 1)
            {
                for (int i = Convert.ToInt32(s.Substring(0, 1)); i <= Convert.ToInt32(s.Substring(2, 3)); i++)
                {
                    switch (Convert.ToString(i))
                    {
                    case "1":
                        InsertSort.Sort(arr);
                        break;

                    case "2":
                        BubbleSort.Sort(arr);
                        break;

                    case "3":
                        QuickSort.Sort(arr, 0, arr.Length - 1);
                        break;

                    case "4":
                        HeapSort.Sort(ref arr);
                        break;

                    case "5":
                        MergeSort.Sort(ref arr, 0, arr.Length - 1);
                        break;
                    }
                }
            }
            else
            {
                switch (s)
                {
                case "1":
                    InsertSort.Sort(arr);
                    break;

                case "2":
                    BubbleSort.Sort(arr);
                    break;

                case "3":
                    QuickSort.Sort(arr, 0, arr.Length - 1);
                    break;

                case "4":
                    HeapSort.Sort(ref arr);
                    break;

                case "5":
                    MergeSort.Sort(ref arr, 0, arr.Length - 1);
                    break;

                case "6":
                    InsertSort.Sort(arr);
                    BubbleSort.Sort(arr);
                    QuickSort.Sort(arr, 0, arr.Length - 1);
                    HeapSort.Sort(ref arr);
                    MergeSort.Sort(ref arr, 0, arr.Length - 1);
                    break;
                }
            }

            Console.ReadLine();
        }
예제 #12
0
        static void Main(string[] args)
        {
            int size  = 20000;
            int range = 10000;

            BubbleSort bubbleSort = new BubbleSort();

            int[] unsortedArray1 = Utils.generateArray(size, range);

            var watch = System.Diagnostics.Stopwatch.StartNew();

            bubbleSort.bubbleSort(unsortedArray1);
            watch.Stop();
            var elapsedMs = watch.Elapsed.TotalMilliseconds;

            Console.WriteLine("bubble took time: " + elapsedMs);

            CountSort countSort = new CountSort();

            int[] unsortedArray2 = Utils.generateArray(size, range);

            watch = System.Diagnostics.Stopwatch.StartNew();
            countSort.countSort(unsortedArray2);
            watch.Stop();
            elapsedMs = watch.Elapsed.TotalMilliseconds;

            Console.WriteLine("count took time: " + elapsedMs);

            MergeSort mergeSort = new MergeSort();

            int[] unsortedArray3 = Utils.generateArray(size, range);

            watch = System.Diagnostics.Stopwatch.StartNew();
            MergeSort.sort(unsortedArray3, 0, unsortedArray3.Length - 1);
            watch.Stop();
            elapsedMs = watch.Elapsed.TotalMilliseconds;

            Console.WriteLine("merge took time: " + elapsedMs);

            InsertionSort insertionSort = new InsertionSort();

            int[] unsortedArray4 = Utils.generateArray(size, range);

            watch = System.Diagnostics.Stopwatch.StartNew();
            insertionSort.insertionSort(unsortedArray4);
            watch.Stop();
            elapsedMs = watch.Elapsed.TotalMilliseconds;

            Console.WriteLine("insertion took time: " + elapsedMs);

            QuickSort quickSort = new QuickSort();

            int[] unsortedArray5 = Utils.generateArray(size, range);

            watch = System.Diagnostics.Stopwatch.StartNew();
            quickSort.quickSort(unsortedArray5);
            watch.Stop();
            elapsedMs = watch.Elapsed.TotalMilliseconds;

            Console.WriteLine("quick took time: " + elapsedMs);


            HeapSort heapSort = new HeapSort();

            int[] unsortedArray6 = Utils.generateArray(size, range);

            watch = System.Diagnostics.Stopwatch.StartNew();
            heapSort.heapSort(unsortedArray6);
            watch.Stop();
            elapsedMs = watch.Elapsed.TotalMilliseconds;

            Console.WriteLine("heap took time: " + elapsedMs);

            SelectionSort selectionSort = new SelectionSort();

            int[] unsortedArray7 = Utils.generateArray(size, range);

            watch = System.Diagnostics.Stopwatch.StartNew();
            selectionSort.selectionSort(unsortedArray7);
            watch.Stop();
            elapsedMs = watch.Elapsed.TotalMilliseconds;

            Console.WriteLine("selection took time: " + elapsedMs);

            Console.ReadKey();
        }
예제 #13
0
 /// <summary>
 /// Sort the specified array.
 /// </summary>
 /// <returns>The sort.</returns>
 /// <param name="a">The array.</param>
 public static void sort(int[] a)
 {
     MergeSort.sortik(a, 0, a.Length - 1);;
 }
        static void Main(string[] args)
        {
            #region Selection Sort

            //The selection sort algorithm sorts an array by repeatedly finding the minimum element(considering ascending order)
            //from unsorted part and putting it at the beginning.The algorithm maintains two subarrays in a given array.

            //1) The subarray which is already sorted.
            //2) Remaining subarray which is unsorted.

            //In every iteration of selection sort, the minimum element(considering ascending order) from the unsorted
            //subarray is picked and moved to the sorted subarray.

            //Time Complexity: O(N^2) as there are two nested loops.
            //Auxiliary Space: O(1)
            //The good thing about selection sort is it never makes more than O(N) swaps and can be useful when memory write is a costly operation.


            //int[] arr = { 64, 25, 12, 22, 11 };
            //SelectionSort.Sort(arr);
            //Console.WriteLine("Sorted array");
            //SelectionSort.PrintArray(arr);
            #endregion

            #region Bubble Sort
            //Bubble Sort is the simplest sorting algorithm that works by repeatedly swapping the adjacent elements if they are in wrong order.
            //Time Complexity: O(N^2)
            //Auxiliary Space: O(1)

            //var watch1 = System.Diagnostics.Stopwatch.StartNew();

            //int[] arr = { 64, 25, 12, 22, 11, 50, 101, 34, 73, 44, 0, 12, 2222 };
            //BubbleSort.Sort(arr);
            //Console.WriteLine("Sorted array");
            //BubbleSort.PrintArray(arr);

            //watch1.Stop();
            //var elapsedMs1 = watch1.ElapsedMilliseconds;

            #endregion

            #region Advanced Bubble Sort
            // The same as Bubble Sort but when a pass goes through without swapping any elements, it stops as they are all sorted.
            //Time Complexity: O(N^2)
            //Auxiliary Space: O(1)

            //var watch2 = System.Diagnostics.Stopwatch.StartNew();

            //int[] arr2 = { 64, 25, 12, 22, 11, 50, 101, 34, 73, 44, 0, 12, 2222 };
            //AdvancedBubbleSort.Sort(arr2);
            //Console.WriteLine("Sorted array");
            //AdvancedBubbleSort.PrintArray(arr2);

            //watch2.Stop();
            //var elapsedMs2 = watch2.ElapsedMilliseconds;
            //Console.WriteLine($"BubbleSort 1: {elapsedMs1}"); // needs Bubble Sort uncommented
            //Console.WriteLine($"BubbleSort 2: {elapsedMs2}");
            #endregion

            #region Insertion Sort

            //Insertion sort is a simple sorting algorithm that works similar to the way you sort playing cards in your hands.
            //The array is virtually split into a sorted and an unsorted part.Values from the unsorted part are picked and placed
            //at the correct position in the sorted part.
            //Algorithm
            //To sort an array of size n in ascending order:
            //1: Iterate from arr[1] to arr[n] over the array.
            //2: Compare the current element(key) to its predecessor.
            //3: If the key element is smaller than its predecessor, compare it to the elements before.Move the greater elements
            //one position up to make space for the swapped element.

            //Time Complexity: O(2N)
            //Auxiliary Space: O(1)

            //var watch2 = System.Diagnostics.Stopwatch.StartNew();

            //int[] arr2 = { 64, 25, 12, 22, 11, 50, 101, 34, 73, 44, 0, 12, 2222 };
            //InsertionSort.Sort(arr2);
            //Console.WriteLine("Sorted array");
            //InsertionSort.PrintArray(arr2);

            //watch2.Stop();
            //var elapsedMs2 = watch2.ElapsedMilliseconds;
            //Console.WriteLine($"InsertionSort: {elapsedMs2}");

            #endregion

            #region Quick Sort
            //Like Merge Sort, QuickSort is a Divide and Conquer algorithm. It picks an element as pivot and partitions the
            //given array around the picked pivot.There are many different versions of quickSort that pick pivot in different ways.

            //Always pick first element as pivot.
            //Always pick last element as pivot (implemented below)
            //Pick a random element as pivot.
            //Pick median as pivot.
            //The key process in quickSort is partition(). Target of partitions is, given an array and an element x of array as pivot,
            //put x at its correct position in sorted array and put all smaller elements(smaller than x) before x, and put all greater
            //elements(greater than x) after x. All this should be done in linear time.

            //Time Complexity O(N^2)
            //Space Complexity O(1)


            //var watch2 = System.Diagnostics.Stopwatch.StartNew();

            //int[] arr2 = { 64, 25, 12, 22, 11, 50, 101, 34, 73, 44, 0, 12, 2222 };
            //QuickSort.Sort(arr2, 0, arr2.Length-1);
            //Console.WriteLine("Sorted array");
            //QuickSort.PrintArray(arr2);

            //watch2.Stop();
            //var elapsedMs2 = watch2.ElapsedMilliseconds;
            //Console.WriteLine($"QuickSort: {elapsedMs2}");

            #endregion

            #region Merge Sort
            //Like QuickSort, Merge Sort is a Divide and Conquer algorithm. It divides input array in two halves, calls itself for
            //the two halves and then merges the two sorted halves.The merge() function is used for merging two halves.The
            //merge(arr, l, m, r) is key process that assumes that arr[l..m] and arr[m + 1..r] are sorted and merges the two sorted
            //sub - arrays into one.

            //The following diagram from wikipedia shows the complete merge sort process for an example array { 38, 27, 43, 3, 9, 82, 10}.
            //If we take a closer look at the diagram, we can see that the array is recursively divided in two halves till the size becomes 1.
            //Once the size becomes 1, the merge processes comes into action and starts merging arrays back till the complete array is merged.

            //Time Complexity O(N * Log N)
            //Space Complexity O(N)


            //var watch2 = System.Diagnostics.Stopwatch.StartNew();

            //int[] arr2 = { 64, 25, 12, 22, 11, 50, 101, 34, 73, 44, 0, 12, 2222 };
            //MergeSort.Sort(arr2, 0, arr2.Length - 1);
            //Console.WriteLine("Sorted array");
            //MergeSort.PrintArray(arr2);

            //watch2.Stop();
            //var elapsedMs2 = watch2.ElapsedMilliseconds;
            //Console.WriteLine($"MergeSort: {elapsedMs2}");
            #endregion

            #region Tim Sort
            //TimSort is a sorting algorithm based on Insertion Sort and Merge Sort.

            //A stable sorting algorithm works in O(n Log n) time
            //Used in Java’s Arrays.sort() as well as Python’s sorted() and sort().
            //First sort small pieces using Insertion Sort, then merges the pieces using merge of merge sort.
            //We divide the Array into blocks known as Run.We sort those runs using insertion sort one by one and then merge those runs using
            //combine function used in merge sort. If the size of Array is less than run, then Array get sorted just by using Insertion Sort.
            //The size of run may vary from 32 to 64 depending upon the size of the array.Note that merge function performs well when sizes
            //subarrays are powers of 2.The idea is based on the fact that insertion sort performs well for small arrays.

            var watch2 = System.Diagnostics.Stopwatch.StartNew();

            int[] arr2 = { 64, 25, 12, 22, 11, 50, 101, 34, 73, 44, 0, 12, 2222 };
            TimSort.Sort(arr2, arr2.Length);
            Console.WriteLine("Sorted array");
            MergeSort.PrintArray(arr2);

            watch2.Stop();
            var elapsedMs2 = watch2.ElapsedMilliseconds;
            Console.WriteLine($"TimSort: {elapsedMs2}");

            #endregion
        }
예제 #15
0
파일: Tester.cs 프로젝트: mtyylx/Basics
        static void Main(string[] args)
        {
            int arraySize = 10;
            int arrayUpperLimits = 100;
            int repeatTimes = 1;
            bool enableLogging = true;

            int[] inputArray;
            double[] executionTime = new double[repeatTimes]; 
            Stopwatch stopwatch = new Stopwatch();

            //Slow - O(n^2)
            InsertionSort mInsertionSort = new InsertionSort();
            SelectionSort mSelectionSort = new SelectionSort();
            BubbleSort mBubbleSort = new BubbleSort();

            //Fast - O(n*lgn)
            MergeSort mMergeSort = new MergeSort();
            HeapSort mHeapSort = new HeapSort();
            QuickSort mQuickSort = new QuickSort();
           
            //Linear - O(n)
            CountingSort mCountingSort = new CountingSort();
            RadixSort mRadixSort = new RadixSort();
            BucketSort mBucketSort = new BucketSort();

            //Test the execution time repeatly.
            for (int i = 0; i < repeatTimes; i++)
            {
                //Always create new Array object, even though the contents are the same.
                //Because each array will be modified at the end of each loop.
                inputArray = ArrayHandler.Create(arraySize, enableLogging, arrayUpperLimits);
                //inputArray = ArrayHandler.CreateAlmostSorted(arraySize, enableLogging);
                //inputArray = new int[] { 122, 44, 122, 55, 33, 55, 44, 23};
                stopwatch.Start();
                //----------------------------------------------------------------------------------------//
                //             A L G O R I T H M         T E S T E D        H E R E                       //
                //----------------------------------------------------------------------------------------//

                //------- 0.Sort in VC# -------
                //Array.Sort(inputArray);                                                         //7ms 10^5

                //#####################################  O(n*n)  #############################################

                //------- 1.Insertion Sort ~ O(n^2) -------
                mInsertionSort.Sort(inputArray);                                                //95ms 10^4
                //mInsertionSort.SortWithTrace(inputArray);
                //mInsertionSort.Sort_Recursive(inputArray);

                //------- 2.Selection Sort ~ O(n^2) -------
                //mSelectionSort.Sort(inputArray);                                                //164ms 10^4
                //mSelectionSort.SortWithTrace(inputArray);

                //------- 3.Bubble Sort ~ O(n^2) -------
                //mBubbleSort.Sort(inputArray);                                                   //600ms 10^4
                //mBubbleSort.OriginalBubbleSort(inputArray);                                     //550ms 10^4

                //###################################  O(n*lgn)  #############################################

                //------- 4.Merge Sort ~ O(n*lgn) -------
                //mMergeSort.Sort(inputArray);                                                    //27ms 10^5
                //mMergeSort.Sort_Enhanced(inputArray);                                           //25ms 10^5

                //------- 5.Heap Sort ~ O(n*lgn) -------
                //mHeapSort.Sort(inputArray);                                                     //53ms 10^5

                //------- 6.Quick Sort ~ O(n*lgn) -------
                //mQuickSort.Sort(inputArray);                                                      //40ms 10^5
                //mQuickSort.Sort_Hoare(inputArray, enableLogging);                               //23ms 10^5
                //mQuickSort.Sort_Lomuto(inputArray, enableLogging);

                //######################################  O(n)  ##############################################

                //------- 7.Counting Sort ~ O(n) -------
                //inputArray = mCountingSort.Sort(inputArray);                                    //2ms 10^5

                //------- 8.Radix Sort ~ O(n) -------
                //inputArray = mRadixSort.Sort(inputArray, enableLogging);                        //114ms 10^5

                //------- 9.Bucket Sort ~ O(n) -------
                //inputArray = mBucketSort.Sort(inputArray);                                      //13ms 10^5

                //------------------------------------------------------------------------------------------
                //             A L G O R I T H M         T E S T        E N D E D
                //------------------------------------------------------------------------------------------
                stopwatch.Stop();
                executionTime[i] = stopwatch.ElapsedMilliseconds;
                Console.Write(executionTime[i] + " ");
                Console.WriteLine("");
                stopwatch.Reset();
                ArrayHandler.Print(inputArray, enableLogging);
            }

            //Print Execution Time
            double ts = executionTime.Average();
            Console.WriteLine("Average Execution Time in milliseconds: " + ts);

            Console.ReadLine();
        }
예제 #16
0
        /// <summary>
        /// Sort the specified array with the algorithm of index i.
        /// </summary>
        /// <returns>The sort.</returns>
        /// <param name="a">The array of integers.</param>
        /// <param name="i">The index of the algorithm.</param>
        static void sort(int[] a, int i)
        {
            switch (i)
            {
            // Bubble Sort.
            case 1:
                // Stores the memory allocated at the moment.
                var mem1 = GC.GetTotalMemory(false);

                // Starts a new stopwatch.
                var watch = System.Diagnostics.Stopwatch.StartNew();

                // Calls the Bubble Sort algorithm.
                BubbleSort.sort(a);

                // Stops the stopwatch.
                watch.Stop();

                // Gets the memory allocated at the moment and sumtracts the
                // older one to get the memory used in the intermediate process.
                var mem2 = GC.GetTotalMemory(false) - mem1;

                // Writes the memory usage in the index of its algorithm in the memory array.
                MainClass.mem[i] = mem2;

                // Gets the value of the stopwatch and stores itin the running time array.
                double time = watch.ElapsedTicks;
                MainClass.eff[i] = time;
                break;

            // Similarly the other cases.
            case 2:
                mem1  = GC.GetTotalMemory(false);
                watch = System.Diagnostics.Stopwatch.StartNew();
                InsertSort.sort(a);
                watch.Stop();
                mem2             = GC.GetTotalMemory(false) - mem1;
                MainClass.mem[i] = mem2;
                time             = watch.ElapsedTicks;
                MainClass.eff[i] = time;
                break;

            case 3:
                mem1  = GC.GetTotalMemory(false);
                watch = System.Diagnostics.Stopwatch.StartNew();
                QuickSort.sort(a);
                watch.Stop();
                mem2             = GC.GetTotalMemory(false) - mem1;
                MainClass.mem[i] = mem2;
                time             = watch.ElapsedTicks;
                MainClass.eff[i] = time;
                break;

            case 4:
                mem1  = GC.GetTotalMemory(false);
                watch = System.Diagnostics.Stopwatch.StartNew();
                HeapSort.sort(a);
                watch.Stop();
                mem2             = GC.GetTotalMemory(false) - mem1;
                MainClass.mem[i] = mem2;
                time             = watch.ElapsedTicks;
                MainClass.eff[i] = time;
                break;

            case 5:
                mem1  = GC.GetTotalMemory(false);
                watch = System.Diagnostics.Stopwatch.StartNew();
                MergeSort.sort(a);
                watch.Stop();
                mem2             = GC.GetTotalMemory(false) - mem1;
                MainClass.mem[i] = mem2;
                time             = watch.ElapsedTicks;
                MainClass.eff[i] = time;
                break;
            }
        }
예제 #17
0
        private static void Execute()
        {
            var random = RandomArray();

            Console.WriteLine("Today's Randomly selected integers are:");
            foreach (var r in random)
            {
                Console.WriteLine(r);
            }

            Seperator();

            var selectionSort = new SelectionSort().Sort(random);

            Console.WriteLine("Utilising Selection Sort:");
            foreach (var selection in selectionSort)
            {
                Console.WriteLine(selection);
            }

            Seperator();

            var insertionSort = new InsertionSort().Sort(random);

            Console.WriteLine("Utilising Insertion Sort:");
            foreach (var insertion in insertionSort)
            {
                Console.WriteLine(insertion);
            }

            Seperator();

            var mergeSort = new MergeSort().Sort(random, 0, random.Length - 1);

            Console.WriteLine("Utilising Merge Sort:");
            var fullMergeWatch = Stopwatch.StartNew();

            foreach (var merge in mergeSort)
            {
                Console.WriteLine(merge);
            }
            fullMergeWatch.Stop();
            var elapsedTime = fullMergeWatch.Elapsed;

            Seperator();

            Console.WriteLine($"A Full cycle of a merge sort takes {elapsedTime} milliseconds");

            Console.WriteLine("One iteration of Selection Sort takes");
            var s = new Stopwatch();

            Console.WriteLine(s.Time(() => new SelectionSort().Sort(random), 1));

            Console.WriteLine("One iteration of Insertion Sort takes");
            var i = new Stopwatch();

            Console.WriteLine(i.Time(() => new InsertionSort().Sort(random), 1));

            Console.WriteLine("One iteration of Merge Sort takes");
            var m = new Stopwatch();

            Console.WriteLine(m.Time(() => new MergeSort().Sort(random, 0, random.Length - 1), 1));

            Seperator();
            TimeTheMethods(random);
        }