-
Notifications
You must be signed in to change notification settings - Fork 294
/
Copy pathBucketSort.cs
58 lines (45 loc) · 1.57 KB
/
BucketSort.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
using System;
using System.Collections.Generic;
using System.Linq;
namespace Advanced.Algorithms.Sorting;
/// <summary>
/// A bucket sort implementation.
/// </summary>
public class BucketSort
{
/// <summary>
/// Sort given integers using bucket sort with merge sort as sub sort.
/// </summary>
public static int[] Sort(int[] array, int bucketSize, SortDirection sortDirection = SortDirection.Ascending)
{
if (bucketSize < 0 || bucketSize > array.Length) throw new Exception("Invalid bucket size.");
var buckets = new Dictionary<int, List<int>>();
int i;
for (i = 0; i < array.Length; i++)
{
if (bucketSize == 0) continue;
var bucketIndex = array[i] / bucketSize;
if (!buckets.ContainsKey(bucketIndex)) buckets.Add(bucketIndex, new List<int>());
buckets[bucketIndex].Add(array[i]);
}
i = 0;
var bucketKeys = new int[buckets.Count];
foreach (var bucket in buckets.ToList())
{
buckets[bucket.Key] = new List<int>(MergeSort<int>
.Sort(bucket.Value.ToArray(), sortDirection));
bucketKeys[i] = bucket.Key;
i++;
}
bucketKeys = MergeSort<int>.Sort(bucketKeys, sortDirection);
var result = new int[array.Length];
i = 0;
foreach (var bucketKey in bucketKeys)
{
var bucket = buckets[bucketKey];
Array.Copy(bucket.ToArray(), 0, result, i, bucket.Count);
i += bucket.Count;
}
return result;
}
}