Exemplo n.º 1
0
        public void ShouldReturnAlreadySortedList()
        {
            var expected = Enumerable.Range(0, 1000).ToArray();

            var actual = Algorithm.Sort(expected);

            Assert.Equal(expected, actual);
        }
Exemplo n.º 2
0
        public async Task Test(ISortAlgorithm algorithm)
        {
            Assert.Equal(new int [] { 2, 4 } as IEnumerable <int>, await algorithm.Sort(new int [] { 4, 2 }));

            var random = new System.Random();

            var random_list = Enumerable.Repeat(0, 1000)
                              .Select(i => random.Next(1, 10)).ToList();

            IEnumerable <int> expected = random_list.OrderBy(i => i);

            Assert.Equal(expected, await algorithm.Sort(random_list));
        }
Exemplo n.º 3
0
        static void Main(string[] args)
        {
            try
            {
                //Console.WriteLine("Please enter your comma separated integer array list. eg: 5,8,3");
                //string arrayString = Console.ReadLine();

                /*Console.ForegroundColor = ConsoleColor.Yellow;
                 * Console.WriteLine("Yelow: Comparing");
                 * Console.ForegroundColor = ConsoleColor.Red;
                 * Console.WriteLine("Red: Exchanged");
                 * Console.ForegroundColor = ConsoleColor.Green;
                 * Console.WriteLine("Green: Not Exchanged\n");
                 * Console.ResetColor();*/
                string   arrayString = "8,7,1,3,6,4,6";
                string[] tokens      = arrayString.Split(',');
                int[]    array       = Array.ConvertAll(tokens, int.Parse);
                Console.WriteLine("Select sort type. Enter one of the number from options");
                foreach (var value in Enum.GetValues(typeof(SortType)))
                {
                    string name = Enum.GetName(typeof(SortType), value);
                    Console.WriteLine("{0} {1}", Convert.ToInt32(value), name);
                }
                var            selectedOption = Convert.ToInt32(Console.ReadLine());
                ISortAlgorithm alg            = SortFactory.GetSortAlgorithm((SortType)selectedOption);
                alg.Sort(array);
                Console.WriteLine("Final: {0}", string.Join(",", array));
                Console.WriteLine("Done");
            }
            catch (Exception ex)
            {
                Console.Write(ex.Message);
            }
            Console.ReadKey();
        }
        private void SortStartExecute(object obj)
        {
            //dynamically create SortAlgorithm instance, from the selected type
            ISortAlgorithm sortAlgorithm = (ISortAlgorithm)Activator.CreateInstance(SelectedSortAlgorithm);

            //start sorting in a new thread
            Task.Run(() => sortAlgorithm.Sort(SortCollection));
        }
Exemplo n.º 5
0
        /// <inheritdoc />
        public void Sort(ISortAlgorithm algorithm, IComparer comparable)
        {
            var array = new object[Count];

            CopyTo(array, 0);

            algorithm.Sort(array, comparable);

            Array.Copy(array, _array, Count);
        }
Exemplo n.º 6
0
 public void SortSessions(IConference conference, List <SessionDisplayModel> sessions)
 {
     if (conference.CanVote())
     {
         _votingSort.Sort(sessions);
     }
     else
     {
         _defaultSort.Sort(sessions);
     }
 }
Exemplo n.º 7
0
        public object Do()
        {
            ISortAlgorithm sortAlgorithm = SortAlgorithmFactory.CreateAlgorithm(_model, _element, _algorithm);
            SortResult     sortResult    = sortAlgorithm.Sort();

            _model.ReorderChildren(_element, sortResult);
            _order = sortResult.Data;

            _model.AssignElementOrder();

            return(null);
        }
Exemplo n.º 8
0
        private void SortBuckets(IEnumerable <List <string> > buckets, CancellationToken cancellationToken)
        {
            foreach (var bucket in buckets.Where(b => b.Any()))
            {
                cancellationToken.ThrowIfCancellationRequested();

                var toSort = bucket.ToArray();
                _sortAlgorithm.Sort(toSort);
                bucket.Clear();
                bucket.AddRange(toSort);
            }
        }
Exemplo n.º 9
0
        private List <string> SortBuckets(List <string>[] buckets)
        {
            var sorted = new List <string>();

            foreach (var bucket in buckets)
            {
                var toSort = bucket.ToArray();
                _sortAlgorithm.Sort(toSort);
                sorted.AddRange(toSort);
            }
            return(sorted);
        }
Exemplo n.º 10
0
        private void Partition(IProgress <ProgressInfo> progress, IDsmElement element, int totalElements, ref int progressedElements)
        {
            ISortAlgorithm algorithm = SortAlgorithmFactory.CreateAlgorithm(_dsmModel, element, PartitionSortAlgorithm.AlgorithmName);

            _dsmModel.ReorderChildren(element, algorithm.Sort());
            progressedElements++;
            UpdateProgress(progress, "Partition elements", totalElements, progressedElements);

            foreach (IDsmElement child in element.Children)
            {
                Partition(progress, child, totalElements, ref progressedElements);
            }
        }
Exemplo n.º 11
0
        private static void AssertSort(int[] array, ISortAlgorithm sortAlgorithm)
        {
            var copy = new int[array.Length];

            array.CopyTo(copy, 0);
            sortAlgorithm.Sort(copy);
            var orderedArray = array.OrderBy(x => x).ToArray();

            for (var i = 0; i < orderedArray.Length; ++i)
            {
                Assert.AreEqual(orderedArray[i], copy[i], $"Invalid element in position: {i} of array: {string.Join(",", array)}s");
            }
        }
Exemplo n.º 12
0
 private void SortBuckets(IEnumerable <List <string> > buckets, CancellationToken cancellationToken)
 {
     foreach (List <string> bucket in buckets)
     {
         cancellationToken.ThrowIfCancellationRequested();
         if (bucket.Any() == false)
         {
             continue;
         }
         string[] toSort = bucket.ToArray();
         _sortAlgorithm.Sort(toSort);
         bucket.Clear();
         bucket.AddRange(toSort);
     }
 }
Exemplo n.º 13
0
        public SortResult <T> OrderObjects <T>(IEnumerable <T> objectsToOrder, ISortAlgorithm <T> sortAlgorithm) where T : AbstractComparable <T>
        {
            if (objectsToOrder == null)
            {
                throw new ArgumentNullException(nameof(objectsToOrder));
            }

            if (sortAlgorithm == null)
            {
                throw new ArgumentNullException(nameof(sortAlgorithm));
            }

            var lowerRanks = objectsToOrder.ToDictionary(k => k, v => new List <T>());

            foreach (var o in objectsToOrder)
            {
                foreach (var hO in o.HigherRankedObjects)
                {
                    List <T> lowerRankList = null;
                    if (lowerRanks.TryGetValue(hO, out lowerRankList))
                    {
                        lowerRankList.Add(o);
                    }
                }
            }

            var results = objectsToOrder
                          .OrderBy(o => o.HigherRankedObjects.Count)
                          .ThenBy(o => lowerRanks[o].Count)
                          .ToArray();
            T left  = null;
            T right = null;

            SortResult <T> sortResult;

            try
            {
                sortResult = sortAlgorithm.Sort(results);
            }
            catch (UnknownComparisonException <T> exception)
            {
                // TODO: Add check that result is the correct length
                left       = exception.Left;
                right      = exception.Right;
                sortResult = new SortResult <T>(results, left, right);
            }
            return(sortResult);
        }
Exemplo n.º 14
0
        public List <Job> GetOrderedJobList(string jobsString)
        {
            if (!_stringValidator.IsValidString(jobsString))
            {
                throw new Exception("Error: wrong syntax");
            }

            var jobs = _jobsBuilder.GetJobList(jobsString);

            if (!_jobsValidator.IsValidListOfJobs(jobs))
            {
                throw new Exception("Error: the job list is not coherent");
            }

            return(_sortAlgorithm.Sort(jobs));
        }
Exemplo n.º 15
0
        public void ExecuteSort_StaticArray_ReturnsSortedArray(ISortAlgorithm <int> sortAlgorithm)
        {
            List <int> staticList = new List <int>
            {
                10,
                3,
                2,
                11,
                1,
                0,
                0
            };

            IEnumerable <int> sortedCollection = sortAlgorithm.Sort(staticList);

            Assert.That(sortedCollection, Is.Ordered);
        }
Exemplo n.º 16
0
        public static void DoTests(IComparable[] arr, ISortAlgorithm sorter)
        {
            var isSorted = TestHelper.IsSortedAsc(arr);

            Assert.IsFalse(isSorted);

            isSorted = TestHelper.IsSortedDesc(arr);
            Assert.IsFalse(isSorted);

            sorter.Sort(arr);
            isSorted = TestHelper.IsSortedAsc(arr);
            Assert.IsTrue(isSorted);

            arr      = arr.Reverse().ToArray();
            isSorted = TestHelper.IsSortedDesc(arr);
            Assert.IsTrue(isSorted);
        }
        /// <summary>
        /// Sorts the specified IList(Of T) using the algorithm specified in the order specified.
        /// </summary>
        /// <typeparam name="T">type of the elements in toSort</typeparam>
        /// <param name="toSort">the list to sort.</param>
        /// <param name="algorithm">The algorithm to use.</param>
        /// <param name="direction">The direction to sort the elements in.</param>
        /// <param name="startIndex">The start index.</param>
        /// <param name="endIndex">The end index.</param>
        /// <param name="compareFunc">The compare func to compare two elements in the list to sort.</param>
        public static void Sort <T>(this IList <T> toSort, SortAlgorithm algorithm, SortDirection direction, int startIndex, int endIndex, Comparison <T> compareFunc)
        {
            if (toSort.IsNullOrEmpty() || (toSort.Count == 1))
            {
                return;
            }

            int startIndexToUse = startIndex;
            int endIndexToUse   = endIndex;

            if (startIndexToUse < 0)
            {
                startIndexToUse = 0;
            }
            if (startIndexToUse >= toSort.Count)
            {
                throw new IndexOutOfRangeException(string.Format("startIndex's value {0} is outside the list to sort, which has {1} values.", startIndexToUse, toSort.Count));
            }
            if (endIndexToUse < 0)
            {
                endIndexToUse = toSort.Count - 1;
            }
            if (endIndexToUse >= toSort.Count)
            {
                throw new IndexOutOfRangeException(string.Format("endIndex's value {0} is outside the list to sort, which has {1} values.", endIndexToUse, toSort.Count));
            }

            Comparison <T> comparisonToUse = compareFunc;

            if (compareFunc == null)
            {
                comparisonToUse = GeneralUtils.GetUsableComparison <T>(null);
            }

            ISortAlgorithm sorter = SortAlgorithmFactory.CreateSortAlgorithmImplementation(algorithm);

            if (sorter != null)
            {
                sorter.Sort(toSort, direction, startIndexToUse, endIndexToUse, comparisonToUse);
            }
        }
Exemplo n.º 18
0
 public T[] Sort()
 {
     return(_sortAlgorithm.Sort <T>(_items.ToArray()));
 }
Exemplo n.º 19
0
 public static int[] HelperSort(ISortAlgorithm algorithm, int[] unsorted)
 {
     return(algorithm.Sort(unsorted));
 }
 protected void SortSubArray(ref T[] subArr)
 {
     SortAlgorithm.Sort(ref subArr);
 }