-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathRadixSort.cs
64 lines (52 loc) · 1.71 KB
/
RadixSort.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
using System.Collections.Generic;
using System.Linq;
namespace Advanced.Algorithms.Sorting
{
/// <summary>
/// A radix sort implementation.
/// </summary>
public class RadixSort
{
public static int[] Sort(int[] array, SortDirection sortDirection = SortDirection.Ascending)
{
int i;
for (i = 0; i < array.Length; i++)
{
if (array[i] < 0)
{
throw new System.Exception("Negative numbers not supported.");
}
}
var @base = 1;
var max = array.Max();
while (max / @base > 0)
{
//create a bucket for digits 0 to 9
var buckets = new List<int>[10];
for (i = 0; i < array.Length; i++)
{
var bucketIndex = array[i] / @base % 10;
if (buckets[bucketIndex] == null)
{
buckets[bucketIndex] = new List<int>();
}
buckets[bucketIndex].Add(array[i]);
}
//now update array with what is in buckets
var orderedBuckets = sortDirection == SortDirection.Ascending ?
buckets : buckets.Reverse();
i = 0;
foreach (var bucket in orderedBuckets.Where(x => x != null))
{
foreach (var item in bucket)
{
array[i] = item;
i++;
}
}
@base *= 10;
}
return array;
}
}
}