forked from aalhour/C-Sharp-Algorithms
-
Notifications
You must be signed in to change notification settings - Fork 0
/
BubbleSorter.cs
48 lines (45 loc) · 1.51 KB
/
BubbleSorter.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
using System.Collections.Generic;
using Algorithms.Common;
namespace Algorithms.Sorting
{
public static class BubbleSorter
{
public static void BubbleSort<T>(this IList<T> collection, Comparer<T> comparer = null)
{
comparer = comparer ?? Comparer<T>.Default;
collection.BubbleSortAscending(comparer);
}
/// <summary>
/// Public API: Sorts ascending
/// </summary>
public static void BubbleSortAscending<T>(this IList<T> collection, Comparer<T> comparer)
{
for (int i = 0; i < collection.Count; i++)
{
for (int index = 0; index < collection.Count - 1; index++)
{
if (comparer.Compare(collection[index], collection[index + 1])>0)
{
collection.Swap(index,index+1);
}
}
}
}
/// <summary>
/// Public API: Sorts descending
/// </summary>
public static void BubbleSortDescending<T>(this IList<T> collection, Comparer<T> comparer)
{
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);
}
}
}
}
}
}