Exemple #1
0
 public SortingTestCase(double timeLimit, Exception expectedException, string description, int[] source, int[] expectedResult, SortingAlgorithm algorithm)
     : base(timeLimit, expectedException, description)
 {
     this.tab       = (int[])source.Clone();
     this.sortedTab = (int[])expectedResult.Clone();
     this.algorithm = algorithm;
 }
        private int TestSortings(SortingAlgorithm algorithm, int[] array)
        {
            var sorter  = SorterFactory.GetSorter();
            var swapped = sorter.Sort(algorithm, array);

            return(swapped);
        }
Exemple #3
0
 public void InitConstructorTests(
     [ValueSource(typeof(DataContext), nameof(DataContext.SortingAlgorithms))] SortingAlgorithm sortingAlgorithm)
 {
     Assert.NotNull(sortingAlgorithm);
     sortingAlgorithm.Sort(DataContext.SimpleArray);
     Assert.Pass();
 }
        //Choosing the right Sorting-Algorithm
        public void SortingAlgorithm(SortingAlgorithmEnum sortingAlgorithmEnum)
        {
            SortingAlgorithm sortingAlgorithm = new SortingAlgorithm(this);

            SortingAlgorithm_UpdateMatrixValuesWithView();
            array = CopyDataGridViewXIn1DimensionalMatrix(sortingTable, NullArray(sortingTable));

            switch (sortingAlgorithmEnum)
            {
            case SortingAlgorithmEnum.Qick:
                sortingAlgorithm.QuickSort(CopyDataGridViewXIn1DimensionalMatrix(sortingTable, NullArray(sortingTable)), 0, array.Length - 1);
                break;

            case SortingAlgorithmEnum.Bubble:
                sortingAlgorithm.BubbleSort(CopyDataGridViewXIn1DimensionalMatrix(sortingTable, NullArray(sortingTable)));
                break;

            case SortingAlgorithmEnum.Insertion:
                sortingAlgorithm.InsertionSort(CopyDataGridViewXIn1DimensionalMatrix(sortingTable, NullArray(sortingTable)));
                break;

            case SortingAlgorithmEnum.Selection:
                sortingAlgorithm.SelectionSort(CopyDataGridViewXIn1DimensionalMatrix(sortingTable, NullArray(sortingTable)));
                break;

            case SortingAlgorithmEnum.Shaker:
                sortingAlgorithm.ShakerSort(CopyDataGridViewXIn1DimensionalMatrix(sortingTable, NullArray(sortingTable)));
                break;
            }

            TransferArrayIntoDataGridView(array, sortingTable, NullArray(sortingTable));
            SortingAlgorithm_UpdateViewWithMatrixValues();
        }
Exemple #5
0
        public SortingTask findOne(int id)
        {
            log.InfoFormat("Entering findOne with value {0}", id);
            IDbConnection con = DBUtils.getConnection();

            using (var comm = con.CreateCommand())
            {
                comm.CommandText = "select id,descriere, Elems, orderC, algoritm from SortingTasks where id=@id";
                IDbDataParameter paramId = comm.CreateParameter();
                paramId.ParameterName = "@id";
                paramId.Value         = id;
                comm.Parameters.Add(paramId);

                using (var dataR = comm.ExecuteReader())
                {
                    if (dataR.Read())
                    {
                        int              idV   = dataR.GetInt32(0);
                        String           desc  = dataR.GetString(1);
                        int              elems = dataR.GetInt32(2);
                        SortingOrder     order = (SortingOrder)Enum.Parse(typeof(SortingOrder), dataR.GetString(3));
                        SortingAlgorithm algo  = (SortingAlgorithm)Enum.Parse(typeof(SortingAlgorithm), dataR.GetString(4));
                        SortingTask      task  = new SortingTask(idV, desc, elems, order, algo);
                        log.InfoFormat("Exiting findOne with value {0}", task);
                        return(task);
                    }
                }
            }
            log.InfoFormat("Exiting findOne with value {0}", null);
            return(null);
        }
            /// <summary>
            /// Note that no ownership is taken over the following:
            /// - Cache
            /// - Topology
            /// - Connections
            /// - Nodes
            /// Hence they must survive the context's lifetime.
            /// The returned context must ONLY be used after the jobhandle is completed. Additionally, this must happen
            /// in the current scope.
            /// </summary>
            public static JobHandle InitializeContext(
                JobHandle inputDependencies,
                out ComputationContext <TTopologyFromVertex> context,
                Database connectionTable,
                TTopologyFromVertex topologies,
                TraversalCache cache,
                NativeArray <TVertex> sourceNodes,
                CacheAPI.VersionTracker version,
                SortingAlgorithm algorithm = SortingAlgorithm.GlobalBreadthFirst
                )
            {
                context       = default;
                context.Cache = new MutableTopologyCache(cache);

                context.Vertices = sourceNodes;

                context.Database   = connectionTable;
                context.Topologies = topologies;

                context.VisitCache =
                    new NativeArray <VertexTools.VisitCache>(context.Vertices.Length, Allocator.TempJob);
                context.VisitCacheLeafIndicies = new NativeList <int>(10, Allocator.TempJob);
                context.Algorithm = algorithm;

                context.Markers = ProfilerMarkers.Markers;

                return(inputDependencies);
            }
        public void Quick_Sort()
        {
            // 3,4,7,9,12,20,21,22,25
            double[] values = new double[1000];
            Random   random = new Random();

            for (int i = 0; i < values.Length; i++)
            {
                int    num = random.Next(0, 200);
                double dec = random.NextDouble();

                double val = num + dec;
                values[i] = val;
            }

            double[] copy = new double[values.Length];
            values.CopyTo(copy, 0);

            SortingAlgorithm sortingAlgorithm = new SortingAlgorithm();

            sortingAlgorithm.QuickSort(values, 0, values.Length - 1);

            copy = copy.OrderBy(x => x).ToArray(); // trusted computing base

            for (int i = 0; i < values.Length; i++)
            {
                Assert.AreEqual(copy[i], values[i]);
            }
        }
Exemple #8
0
        public IEnumerable <SortingTask> findAll()
        {
            IDbConnection       con    = DBUtils.getConnection();
            IList <SortingTask> tasksR = new List <SortingTask>();

            using (var comm = con.CreateCommand())
            {
                comm.CommandText = "select id,descriere, Elems, orderC, algoritm from SortingTasks";

                using (var dataR = comm.ExecuteReader())
                {
                    while (dataR.Read())
                    {
                        int              idV   = dataR.GetInt32(0);
                        String           desc  = dataR.GetString(1);
                        int              elems = dataR.GetInt32(2);
                        SortingOrder     order = (SortingOrder)Enum.Parse(typeof(SortingOrder), dataR.GetString(3));
                        SortingAlgorithm algo  = (SortingAlgorithm)Enum.Parse(typeof(SortingAlgorithm), dataR.GetString(4));
                        SortingTask      task  = new SortingTask(idV, desc, elems, order, algo);
                        tasksR.Add(task);
                    }
                }
            }

            return(tasksR);
        }
Exemple #9
0
        private void GraphPoints(uint count)
        {
            chart1.ResetAutoValues();

            int [] points;
            switch (comboBox1.SelectedItem.ToString())
            {
            case "Random":
                points = GetRandomPoints(count);
                break;

            case "Sorted":
                points = GetSortedPoints(count);
                break;

            case "Reversed":
                points = GetReversedPoints(count);
                break;

            default:
                points = new int[0];
                break;
            }

            SortingAlgorithm[] algorithms = new SortingAlgorithm[]
            {
                new BubbleSort(),
                new InsertionSort(),
                new SelectionSort(),
                new MergeSort(),
                new QuickSort()
            };

            int i = 0;

            foreach (SortingAlgorithm algorithm in algorithms)
            {
                this.Text = string.Format("Running algorithm: {0}", algorithm.GetType().Name);

                int[] cloned = new int[points.Length];
                Array.Copy(points, cloned, points.Length);

                algorithm.Sort(cloned);
                i++;

                Series series = chart1.Series.Add(algorithm.GetType().Name + " " + i.ToString());

                if (cbOperation.SelectedItem.ToString() == "Comparisons")
                {
                    series.Points.Add(new double[] { algorithm.Comparisons });
                }
                else
                {
                    series.Points.Add(new double[] { algorithm.Swaps });
                }
            }

            this.Text = string.Format("Ready");
        }
        public void ReverseArray()
        {
            SortingAlgorithm sortingAlgorithm = new SortingAlgorithm(this);

            array = CopyDataGridViewXIn1DimensionalMatrix(sortingTable, NullArray(sortingTable));
            sortingAlgorithm.Reverse(array);
            TransferArrayIntoDataGridView(array, sortingTable, NullArray(sortingTable));
        }
Exemple #11
0
        public void BubbleSort()
        {
            int[] numbersForSorting = { 65, 37, 11, 20, 45, 84, 24, 14, 3 };
            int[] sortedNumbers     = { 3, 11, 14, 20, 24, 37, 45, 65, 84 };
            int[] result            = SortingAlgorithm.BubbleSort(numbersForSorting);

            Assert.Equal(sortedNumbers, result);
        }
        public void QuickSortTest()
        {
            int[] arr   = { 12, 2, 34, 6, 23, 7, 5, 2 }; // TODO: 初始化为适当的值
            int   left  = 0;                             // TODO: 初始化为适当的值
            int   right = arr.Length - 1;                // TODO: 初始化为适当的值

            SortingAlgorithm.QuickSort(arr, left, right);
            //Assert.Inconclusive("无法验证不返回值的方法。");
        }
 public PlayerStatsPage(IEnumerable <Team> teams)
 {
     DataContext = this;
     InitializeComponent();
     SubHeader.Visibility = Visibility.Collapsed;
     PlayersDataGrid.AutoGenerateColumns = false;
     PlayersDataGrid.ItemsSource         = SortingAlgorithm.Sort(teams, SortingAlgorithm.PlayerSortByTypes.Goal, true);
     _leagueService = new LeagueService();
     Header.Text    = _leagueService.GetAll().First(x => x.TeamIds.Contains(teams.First().Id)).Name.Value;
 }
        public void QsortTest_SortFullRandomArray()
        {
            int[] value = Enumerable.Range(0, 100).Reverse().ToArray();

            int[] expected = value.Reverse().ToArray();

            SortingAlgorithm.Qsort(value, 0, value.Length - 1);

            CollectionAssert.Equals(value, expected);
        }
        public void QsortTest_SortFullDefinedArray()
        {
            int[] value = new[] { -10, 0, 3, -11, 2, 7, 12 };

            int[] expected = new[] { -11, -10, 0, 2, 3, 7, 12 };

            SortingAlgorithm.Qsort(value, 0, value.Length - 1);

            CollectionAssert.Equals(value, expected);
        }
Exemple #16
0
        static void Main(string[] args)
        {
            int[] array = new int[] { 0, 5, 4, 9, 8, 1, 7, 2, 3 };
            //    int[] array = new int[] { 1, 3, 2, 3, 2, 1, 1, 2, 3 };

            SortingAlgorithm.InsertionSort(array);
            var noOfExchange = SortingAlgorithm.noOfEchange;

            Console.WriteLine();
        }
Exemple #17
0
        public void AssertSorting <T>(T[] array, SortingAlgorithm sortingAlgorithm) where T : IComparable
        {
            Assert.NotNull(sortingAlgorithm);
            var testArray = array.Clone() as T[];

            sortingAlgorithm.Sort(array);
            Assert.NotNull(array);
            Assert.IsTrue(array.Length == testArray.Length);
            Assert.IsTrue(Common.IsSorted(array));
            Assert.Pass();
        }
 static void Main(string[] args)
 {
     int[] arr = new int[] { 6, 4, 5, 4, 3, 7, 2 };
     SortingAlgorithm<int> algo = new SortingAlgorithm<int>();
     int[] sortedArray = algo.Sort(arr);
     foreach (int item in sortedArray)
     {
         Console.Write(item + " ");
     }
     Console.ReadLine();
 }
        static void Main(string[] args)
        {
            int[] arr = new int[] { 6, 4, 5, 4, 3, 7, 2 };
            SortingAlgorithm <int> algo = new SortingAlgorithm <int>();

            int[] sortedArray = algo.Sort(arr);
            foreach (int item in sortedArray)
            {
                Console.Write(item + " ");
            }
            Console.ReadLine();
        }
Exemple #20
0
        public void SortElementsMethod_ReturnProperValue()
        {
            //Arrange
            var unsortedVal = "wyraz12 wyraz3 wy21raz";
            var expected    = "wyraz3 wyraz12 wy21raz";

            // Act
            var actual = SortingAlgorithm.SortStrByDigits(unsortedVal);

            //Assert
            Assert.AreEqual(expected, actual);
        }
Exemple #21
0
        public void SortElementsMethod_ReturnProperValueWithArgHave5Words()
        {
            //Arrange
            var unsortedVal = "wyraz124 wyraz335 wy0raz 654wyraz 2wyrazy";
            var expected    = "wy0raz 2wyrazy wyraz124 wyraz335 654wyraz";

            // Act
            var actual = SortingAlgorithm.SortStrByDigits(unsortedVal);

            //Assert
            Assert.AreEqual(expected, actual);
        }
        public static SortingSession <T> CreateSession(Algorithm algorithm, Func <T, T, Task <int> > comparator, IEnumerable <T> items)
        {
            SortingAlgorithm <T> sortingAlgorithm = null;

            switch (algorithm)
            {
            case Algorithm.BuiltinListSort:
                sortingAlgorithm = new BuiltinListSortAlgorithm <T>(comparator);
                break;
            }
            return(new SortingSession <T>(sortingAlgorithm, items));
        }
        private void createSortingThreads()
        {
            SortingAlgorithm topSorter    = sorterFactory.SortingAlgorithmFactory.create(btnSortingAlgorithm1.Text);
            SortingAlgorithm bottomSorter = sorterFactory.SortingAlgorithmFactory.create(btnSortingAlgorithm2.Text);

            stopwatch1 = new Stopwatch();
            stopwatch2 = new Stopwatch();

            int speed = speedTrackBar.Value;

            // Kreiranje niti za gornji sorter tako sto konstruktoru prosljedjujemo
            // lambda izraz u kome pocinjemo sortiranje i oznacavamo da je zavrseno sortiranje kada se zavrsi
            //
            topThread = new System.Threading.Thread(() =>
            {
                topSorter.sort(topArray, speed);
                topIsSorting = false;
            });

            // Kreiranje niti za donji sorter tako sto konstruktoru prosljedjujemo
            // lambda izraz u kome pocinjemo sortiranje i oznacavamo da je zavrseno sortiranje kada se zavrsi
            //
            bottomThread = new System.Threading.Thread(() =>
            {
                bottomSorter.sort(bottomArray, speed);
                bottomIsSorting = false;
            });


            // Paralelno pokrecemo obje niti
            //
            Parallel.Invoke(
                () =>
            {
                topIsSorting = true;
                topThread.Start();
            },
                () =>
            {
                bottomIsSorting = true;
                bottomThread.Start();
            }
                );

            // Stoperice i tajmeri se ne pokrecu paralelno jer su njihovi procesi vezani za UI nit
            //
            stopwatch1.Start();
            stopwatch2.Start();
            //
            timer1.Start();
            timer2.Start();
        }
    /*
     * Depending on what button the user pressed, this method instantiates the corresponding algorithm.
     */
    private void InstantiateSort()
    {
        switch (AlgorithmDetails.Algorithm)
        {
        case 1:
            ActiveSort = Instantiate(SelectionSort);
            break;

        case 2:
            ActiveSort = Instantiate(BubbleSort);
            break;
        }
    }
        public void DescendingMinElementSortTests()
        {
            for (int j = 0; j < 10; j++)
            {
                var array = TestHelper.GenerateJaggedArray(Guid.NewGuid().GetHashCode());
                //// TestHelper.Track(array, $"---------------------------\nUnsorted array {j + 1}:");

                SortingAlgorithm.Sort(array, new DescendingMinElementComparator());
                //// TestHelper.Track(array, $"Sorted array {j + 1}:");

                Assert.IsTrue(TestHelper.IsXscendingOrder(array, arr => arr.Min(), (a, b) => a < b));
            }
        }
Exemple #26
0
    private void Start()
    {
        sortingAlgorithm = new SortingAlgorithm <int>();
        binaryPile       = new BinaryPile <int>();

        sortingAlgorithm.sortingOrder = SortingOrder.ascendant;


        for (int i = 0; i < 20; i++)
        {
            binaryPile.Add(Random.Range(0, 100));
        }
    }
        public void QsortBigRandomArray()
        {
            Random randomKey = new Random();

            int[] array = Enumerable.Range(-500000, 1000000).OrderBy(x => randomKey.Next()).ToArray();

            int[] expected = new int[array.Length];

            Array.Copy(array, expected, array.Length);
            Array.Sort(expected);

            SortingAlgorithm.Qsort(array, 0, array.Length - 1);

            CollectionAssert.AreEqual(array, expected);
        }
        private static void RunSortAlgorithm(Object o, SortingAlgorithm alg)
        {
            var       vehicles = (SortableItem <Car>[])o;
            Stopwatch sw       = new Stopwatch();

            string algorithm = "Unknown";
            SortingAlgorithm <SortableItem <Car>, Car> s1 = null;

            switch (alg)
            {
            case SortingAlgorithm.BubbleSort:
                algorithm = "BubbleSort";
                s1        = new BubbleSort <Car>();
                break;

            case SortingAlgorithm.SelectionSort:
                algorithm = "SelectionSort";
                s1        = new SelectionSort <Car>();
                break;

            case SortingAlgorithm.InsertionSort:
                algorithm = "InsertionSort";
                s1        = new InsertionSort <Car>();
                break;

            case SortingAlgorithm.MergeSort:
                algorithm = "MergeSort";
                s1        = new MergeSort <Car>();
                break;

            case SortingAlgorithm.QuickSort:
                algorithm = "QuickSort";
                s1        = new QuickSort <Car>();
                break;

            default:
                break;
            }

            if (s1 != null)
            {
                sw.Start();
                s1.Sort(ref vehicles);
                sw.Stop();
            }

            ShowElapsedTime(sw.Elapsed.TotalMilliseconds, algorithm);
        }
Exemple #29
0
        public static void Main(string[] args)
        {
            int[] arr = new int[] { 3, -1, 15, 4, 17, 2, 33, 0 };
            Console.WriteLine("array = [{0}]", string.Join(", ", arr));
            SortingAlgorithm.SelectionSort(arr);
            Console.WriteLine("sorted array = [{0}]", string.Join(", ", arr));

            //SortingAlgorithm.SelectionSort(new int[0]); // Test sorting empty array
            //SortingAlgorithm.SelectionSort(new int[1]); // Test sorting single element array

            Console.WriteLine(SearchingAlgorithm.BinarySearch(arr, -1000));
            Console.WriteLine(SearchingAlgorithm.BinarySearch(arr, 0));
            Console.WriteLine(SearchingAlgorithm.BinarySearch(arr, 17));
            Console.WriteLine(SearchingAlgorithm.BinarySearch(arr, 10));
            Console.WriteLine(SearchingAlgorithm.BinarySearch(arr, 1000));
        }
Exemple #30
0
        public void QuickSort_Random_LargeArray_Test()
        {
            double[] array = SortingAlgorithm <double> .CreateDoubleRandomArray(5000);

            double[] expectedArr = new double[5000];

            for (int i = 0; i < array.Length; i++)
            {
                expectedArr[i] = array[i];
            }

            _sortingContext.SetAlgorithm(new QuickSortAlgorithm <double>(array));
            _sortingContext.Sort();

            CollectionAssert.AreEquivalent(expectedArr, array);
        }
Exemple #31
0
        public void MergeSort_Random_LargeArray_Test()
        {
            int[] array = SortingAlgorithm <int> .CreateInt32RandomArray(5000);

            int[] expectedArr = new int[5000];

            for (int i = 0; i < array.Length; i++)
            {
                expectedArr[i] = array[i];
            }

            _sortingContext.SetAlgorithm(new MergeSortAlgorithm <int>(array));
            _sortingContext.Sort();

            CollectionAssert.AreEquivalent(expectedArr, array);
        }
 public SortingScenario(SortingAlgorithm sortingAlgorithm, int numElements, SortInputType sortInputType)
 {
     this.SortingAlgorithm = sortingAlgorithm;
     this.NumElements = numElements;
     this.SortInputType = sortInputType;
 }