-
Notifications
You must be signed in to change notification settings - Fork 1.4k
/
SelectionSorter.cs
48 lines (45 loc) · 1.46 KB
/
SelectionSorter.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 SelectionSorter
{
public static void SelectionSort<T>(this IList<T> collection, Comparer<T> comparer = null)
{
comparer = comparer ?? Comparer<T>.Default;
collection.SelectionSortAscending(comparer);
}
/// <summary>
/// Public API: Sorts ascending
/// </summary>
public static void SelectionSortAscending<T>(this IList<T> collection, Comparer<T> comparer)
{
int i;
for(i=0;i<collection.Count;i++){
int min=i;
for (int j = i + 1; j < collection.Count; j++) {
if (comparer.Compare(collection[j], collection[min])<0)
min=j;
}
collection.Swap(i,min);
}
}
/// <summary>
/// Public API: Sorts ascending
/// </summary>
public static void SelectionSortDescending<T>(this IList<T> collection, Comparer<T> comparer)
{
int i;
for (i = collection.Count-1; i >0; i--)
{
int max = i;
for (int j = 0; j <=i; j++)
{
if (comparer.Compare(collection[j], collection[max]) < 0)
max = j;
}
collection.Swap(i, max);
}
}
}
}