-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathBucketSort.java
66 lines (57 loc) · 1.45 KB
/
BucketSort.java
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
package codingProblems;
import java.util.ArrayList;
import java.util.List;
public class BucketSort
{
private static final int DEFAULT_BUCKET_SIZE = 5;
public static void sort(Integer[] array)
{
sort(array, DEFAULT_BUCKET_SIZE);
}
public static void sort(Integer[] array, int bucketSize)
{
if (array.length == 0)
{
return;
}
// Determine minimum and maximum values
Integer minValue = array[0];
Integer maxValue = array[0];
for (int i = 1; i < array.length; i++)
{
if (array[i] < minValue)
{
minValue = array[i];
} else if (array[i] > maxValue)
{
maxValue = array[i];
}
}
// Initialise buckets
int bucketCount = (maxValue - minValue) / bucketSize + 1;
List<List<Integer>> buckets = new ArrayList<List<Integer>>(bucketCount);
for (int i = 0; i < bucketCount; i++)
{
buckets.add(new ArrayList<Integer>());
}
// Distribute input array values into buckets
for (int i = 0; i < array.length; i++)
{
buckets.get((array[i] - minValue) / bucketSize).add(array[i]);
}
// Sort buckets and place back into input array
int currentIndex = 0;
for (int i = 0; i < buckets.size(); i++)
{
Integer[] bucketArray = new Integer[buckets.get(i).size()];
bucketArray = buckets.get(i).toArray(bucketArray);
InsertionSort.sort(bucketArray);
for (int j = 0; j < bucketArray.length; j++) {
array[currentIndex++] = bucketArray[j];
}
}
}
public static void main(String args[])
{
}
}