From 72a80a40abf6b618524a3d3785a18ad7678295d9 Mon Sep 17 00:00:00 2001 From: Xiaodi Yan Date: Sun, 10 May 2020 21:14:45 +1200 Subject: [PATCH] Fix the BubbleSorter and add the unit test. --- Algorithms/Sorting/BubbleSorter.cs | 10 +++++----- UnitTest/AlgorithmsTests/BubbleSorterTest.cs | 21 ++++++++++++++++++++ 2 files changed, 26 insertions(+), 5 deletions(-) create mode 100644 UnitTest/AlgorithmsTests/BubbleSorterTest.cs diff --git a/Algorithms/Sorting/BubbleSorter.cs b/Algorithms/Sorting/BubbleSorter.cs index 1a2e31c6..83981475 100644 --- a/Algorithms/Sorting/BubbleSorter.cs +++ b/Algorithms/Sorting/BubbleSorter.cs @@ -18,11 +18,11 @@ public static void BubbleSortAscending(this IList collection, Comparer { for (int i = 0; i < collection.Count; i++) { - for (int index = 0; index < collection.Count - 1; index++) + for (int index = 0; index < collection.Count - i - 1; index++) { - if (comparer.Compare(collection[index], collection[index + 1])>0) + if (comparer.Compare(collection[index], collection[index + 1]) > 0) { - collection.Swap(index,index+1); + collection.Swap(index, index + 1); } } } @@ -33,13 +33,13 @@ public static void BubbleSortAscending(this IList collection, Comparer /// public static void BubbleSortDescending(this IList collection, Comparer comparer) { - for (int i = 0; i < collection.Count-1; i++) + for (int i = 0; i < collection.Count - 1; i++) { for (int index = 1; index < collection.Count - i; index++) { if (comparer.Compare(collection[index], collection[index - 1]) > 0) { - collection.Swap(index-1, index); + collection.Swap(index - 1, index); } } } diff --git a/UnitTest/AlgorithmsTests/BubbleSorterTest.cs b/UnitTest/AlgorithmsTests/BubbleSorterTest.cs new file mode 100644 index 00000000..9dfbcf3c --- /dev/null +++ b/UnitTest/AlgorithmsTests/BubbleSorterTest.cs @@ -0,0 +1,21 @@ +using Algorithms.Sorting; +using System.Collections.Generic; +using System.Linq; +using Xunit; + +namespace UnitTest.AlgorithmsTests +{ + public static class BubbleSorterTest + { + [Fact] + public static void DoTest() + { + var list = new List() { 23, 42, 4, 16, 8, 15, 3, 9, 55, 0, 34, 12, 2, 46, 25 }; + list.BubbleSort(); + Assert.True(list.SequenceEqual(list.OrderBy(x => x)), "Wrong BubbleSort ascending"); + + list.BubbleSortDescending(Comparer.Default); + Assert.True(list.SequenceEqual(list.OrderByDescending(x => x)), "Wrong BubbleSort descending"); + } + } +}