forked from kelvins/algorithms-and-data-structures
-
Notifications
You must be signed in to change notification settings - Fork 0
/
BucketSort.java
45 lines (37 loc) · 975 Bytes
/
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
public class BucketSort {
/**
* @param vetor Vetor que será ordenado /** Aplica a ordenação BucketSorte no vetor
*/
public int[] sort(int[] vetor) {
final int[] code = hash(vetor);
List<Integer>[] buckets = new List[code[1]];
for (int i = 0; i < code[1]; i++) {
buckets[i] = new ArrayList<Integer>();
}
for (int i : vetor) {
buckets[hash(i, code)].add(i);
}
for (List bucket : buckets) {
Collections.sort(bucket);
}
int ndx = 0;
for (int b = 0; b < buckets.length; b++) {
for (int v : buckets[b]) {
vetor[ndx++] = v;
}
}
return vetor;
}
private int[] hash(int[] input) {
int m = input[0];
for (int i = 1; i < input.length; i++) {
if (m < input[i]) {
m = input[i];
}
}
return new int[] {m, (int) Math.sqrt(input.length)};
}
private int hash(int i, int[] code) {
return (int) ((double) i / code[0] * (code[1] - 1));
}
}