Skip to content

Commit

Permalink
Merge pull request aalhour#136 from yanxiaodi/xy-fix-bubbleSorter
Browse files Browse the repository at this point in the history
Fix the BubbleSorter and add the unit test.
  • Loading branch information
aalhour authored May 27, 2020
2 parents ad09171 + 72a80a4 commit 504140e
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 5 deletions.
10 changes: 5 additions & 5 deletions Algorithms/Sorting/BubbleSorter.cs
Original file line number Diff line number Diff line change
Expand Up @@ -18,11 +18,11 @@ public static void BubbleSortAscending<T>(this IList<T> collection, Comparer<T>
{
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);
}
}
}
Expand All @@ -33,13 +33,13 @@ public static void BubbleSortAscending<T>(this IList<T> collection, Comparer<T>
/// </summary>
public static void BubbleSortDescending<T>(this IList<T> collection, Comparer<T> 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);
}
}
}
Expand Down
21 changes: 21 additions & 0 deletions UnitTest/AlgorithmsTests/BubbleSorterTest.cs
Original file line number Diff line number Diff line change
@@ -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<int>() { 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<int>.Default);
Assert.True(list.SequenceEqual(list.OrderByDescending(x => x)), "Wrong BubbleSort descending");
}
}
}

0 comments on commit 504140e

Please sign in to comment.