Exemple #1
0
        public void SortTest()
        {
            var quickSort = ISortFactory.GetSort(Sort.QuickSort);

            List <int> input = null;

            quickSort.Sort(input);
            Assert.IsNull(input);

            input = new List <int>();
            quickSort.Sort(input);
            Assert.AreEqual(0, input.Count);

            input = new List <int> {
                5
            };
            quickSort.Sort(input);
            Assert.AreEqual(1, input.Count);
            Assert.AreEqual(5, input[0]);

            input = new List <int> {
                5, 4, 1, 8, 6, 7, 3, 5, 0, 9, 1, 2, 5, 3
            };
            quickSort.Sort(input);
            Assert.AreEqual(14, input.Count);

            var expected = new List <int> {
                0, 1, 1, 2, 3, 3, 4, 5, 5, 5, 6, 7, 8, 9
            };

            for (var i = 0; i < 14; i++)
            {
                Assert.AreEqual(expected[i], input[i]);
            }
        }
Exemple #2
0
        public static Tree CreateBinarySearchTree(List <int> input, bool isInputOrdered = false)
        {
            var length = input?.Count ?? 0;

            if (length == 0)
            {
                return(null);
            }

            if (length == 1)
            {
                return(new Tree(input[0]));
            }

            if (!isInputOrdered)
            {
                var quickSort = ISortFactory.GetSort(Sort.QuickSort);
                quickSort.Sort(input);
            }

            var halfLength = length / 2;
            var inputLeft  = input.GetRange(0, halfLength);
            var inputRight = input.GetRange(halfLength + 1, (Math.Min(halfLength, length - 1 - halfLength)));

            return(new Tree(input[halfLength])
            {
                Left = CreateBinarySearchTree(inputLeft, true),
                Right = CreateBinarySearchTree(inputRight, true)
            });
        }