- Notifications
You must be signed in to change notification settings - Fork 1.4k
/
Copy pathBucketSorter.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
usingSystem.Collections.Generic;
usingSystem.Linq;
namespaceAlgorithms.Sorting
{
/// <summary>
/// Only support IList<int> Sort
/// </summary>
publicstaticclassBucketSorter
{
publicstaticvoidBucketSort(thisIList<int>collection)
{
collection.BucketSortAscending();
}
/// <summary>
/// Public API: Sorts ascending
/// </summary>
publicstaticvoidBucketSortAscending(thisIList<int>collection)
{
intmaxValue=collection.Max();
intminValue=collection.Min();
List<int>[]bucket=newList<int>[maxValue-minValue+1];
for(inti=0;i<bucket.Length;i++)
{
bucket[i]=newList<int>();
}
foreach(intiincollection){
bucket[i-minValue].Add(i);
}
intk=0;
foreach(List<int>iinbucket){
if(i.Count>0)
{
foreach(intjini)
{
collection[k]=j;
k++;
}
}
}
}
/// <summary>
/// Public API: Sorts descending
/// </summary>
publicstaticvoidBucketSortDescending(thisIList<int>collection)
{
intmaxValue=collection[0];
intminValue=collection[0];
for(inti=1;i<collection.Count;i++)
{
if(collection[i]>maxValue)
maxValue=collection[i];
if(collection[i]<minValue)
minValue=collection[i];
}
List<int>[]bucket=newList<int>[maxValue-minValue+1];
for(inti=0;i<bucket.Length;i++)
{
bucket[i]=newList<int>();
}
foreach(intiincollection)
{
bucket[i-minValue].Add(i);
}
intk=collection.Count-1;
foreach(List<int>iinbucket)
{
if(i.Count>0)
{
foreach(intjini)
{
collection[k]=j;
k--;
}
}
}
}
}
}