forked from aalhour/C-Sharp-Algorithms
-
Notifications
You must be signed in to change notification settings - Fork 0
/
BucketSorter.cs
89 lines (78 loc) · 2.38 KB
/
BucketSorter.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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
using System.Collections.Generic;
using System.Linq;
namespace Algorithms.Sorting
{
/// <summary>
/// Only support IList<int> Sort
/// </summary>
public static class BucketSorter
{
public static void BucketSort(this IList<int> collection)
{
collection.BucketSortAscending();
}
/// <summary>
/// Public API: Sorts ascending
/// </summary>
public static void BucketSortAscending(this IList<int> collection)
{
int maxValue = collection.Max();
int minValue = collection.Min();
List<int>[] bucket = new List<int>[maxValue - minValue + 1];
for (int i = 0; i < bucket.Length; i++)
{
bucket[i] = new List<int>();
}
foreach (int i in collection) {
bucket[i - minValue].Add(i);
}
int k = 0;
foreach (List<int> i in bucket) {
if (i.Count > 0)
{
foreach (int j in i)
{
collection[k] = j;
k++;
}
}
}
}
/// <summary>
/// Public API: Sorts descending
/// </summary>
public static void BucketSortDescending(this IList<int> collection)
{
int maxValue = collection[0];
int minValue = collection[0];
for (int i = 1; i < collection.Count; i++)
{
if (collection[i] > maxValue)
maxValue = collection[i];
if (collection[i] < minValue)
minValue = collection[i];
}
List<int>[] bucket = new List<int>[maxValue - minValue + 1];
for (int i = 0; i < bucket.Length; i++)
{
bucket[i] = new List<int>();
}
foreach (int i in collection)
{
bucket[i - minValue].Add(i);
}
int k = collection.Count-1;
foreach (List<int> i in bucket)
{
if (i.Count > 0)
{
foreach (int j in i)
{
collection[k] = j;
k--;
}
}
}
}
}
}