Skip to content

Commit 504140e

Browse files
authored
Merge pull request aalhour#136 from yanxiaodi/xy-fix-bubbleSorter
Fix the BubbleSorter and add the unit test.
2 parents ad09171 + 72a80a4 commit 504140e

File tree

2 files changed

+26
-5
lines changed

2 files changed

+26
-5
lines changed

Algorithms/Sorting/BubbleSorter.cs

+5-5
Original file line numberDiff line numberDiff line change
@@ -18,11 +18,11 @@ public static void BubbleSortAscending<T>(this IList<T> collection, Comparer<T>
1818
{
1919
for (int i = 0; i < collection.Count; i++)
2020
{
21-
for (int index = 0; index < collection.Count - 1; index++)
21+
for (int index = 0; index < collection.Count - i - 1; index++)
2222
{
23-
if (comparer.Compare(collection[index], collection[index + 1])>0)
23+
if (comparer.Compare(collection[index], collection[index + 1]) > 0)
2424
{
25-
collection.Swap(index,index+1);
25+
collection.Swap(index, index + 1);
2626
}
2727
}
2828
}
@@ -33,13 +33,13 @@ public static void BubbleSortAscending<T>(this IList<T> collection, Comparer<T>
3333
/// </summary>
3434
public static void BubbleSortDescending<T>(this IList<T> collection, Comparer<T> comparer)
3535
{
36-
for (int i = 0; i < collection.Count-1; i++)
36+
for (int i = 0; i < collection.Count - 1; i++)
3737
{
3838
for (int index = 1; index < collection.Count - i; index++)
3939
{
4040
if (comparer.Compare(collection[index], collection[index - 1]) > 0)
4141
{
42-
collection.Swap(index-1, index);
42+
collection.Swap(index - 1, index);
4343
}
4444
}
4545
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
using Algorithms.Sorting;
2+
using System.Collections.Generic;
3+
using System.Linq;
4+
using Xunit;
5+
6+
namespace UnitTest.AlgorithmsTests
7+
{
8+
public static class BubbleSorterTest
9+
{
10+
[Fact]
11+
public static void DoTest()
12+
{
13+
var list = new List<int>() { 23, 42, 4, 16, 8, 15, 3, 9, 55, 0, 34, 12, 2, 46, 25 };
14+
list.BubbleSort();
15+
Assert.True(list.SequenceEqual(list.OrderBy(x => x)), "Wrong BubbleSort ascending");
16+
17+
list.BubbleSortDescending(Comparer<int>.Default);
18+
Assert.True(list.SequenceEqual(list.OrderByDescending(x => x)), "Wrong BubbleSort descending");
19+
}
20+
}
21+
}

0 commit comments

Comments
 (0)