-
Notifications
You must be signed in to change notification settings - Fork 294
/
Copy pathCountingSort.cs
68 lines (56 loc) · 1.73 KB
/
CountingSort.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
using System;
using System.Collections.Generic;
namespace Advanced.Algorithms.Sorting;
/// <summary>
/// A counting sort implementation.
/// </summary>
public class CountingSort
{
/// <summary>
/// Sort given integers.
/// </summary>
public static int[] Sort(IEnumerable<int> enumerable, SortDirection sortDirection = SortDirection.Ascending)
{
var lengthAndMax = GetLengthAndMax(enumerable);
var length = lengthAndMax.Item1;
var max = lengthAndMax.Item2;
//add one more space for zero
var countArray = new int[max + 1];
//count the appearances of elements
foreach (var item in enumerable)
{
if (item < 0) throw new Exception("Negative numbers not supported.");
countArray[item]++;
}
//now aggregate and assign the sum from left to right
var sum = countArray[0];
for (var i = 1; i <= max; i++)
{
sum += countArray[i];
countArray[i] = sum;
}
var result = new int[length];
//now assign result
foreach (var item in enumerable)
{
var index = countArray[item];
result[sortDirection == SortDirection.Ascending ? index - 1 : result.Length - index] = item;
countArray[item]--;
}
return result;
}
/// <summary>
/// Get Max of given array.
/// </summary>
private static Tuple<int, int> GetLengthAndMax(IEnumerable<int> array)
{
var length = 0;
var max = int.MinValue;
foreach (var item in array)
{
length++;
if (item.CompareTo(max) > 0) max = item;
}
return new Tuple<int, int>(length, max);
}
}