-
Notifications
You must be signed in to change notification settings - Fork 379
Expand file tree
/
Copy pathBucketSort.java
More file actions
43 lines (36 loc) · 1.23 KB
/
Copy pathBucketSort.java
File metadata and controls
43 lines (36 loc) · 1.23 KB
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
// Bucket Sort Algorithm in Java
// Time Complexity: O(n + k)
// Works best for uniformly distributed data between 0 and 1.
import java.util.*;
public class BucketSort {
public static void sort(float[] arr) {
int n = arr.length;
if (n <= 0)
return;
// Create empty buckets
@SuppressWarnings("unchecked")
Vector<Float>[] buckets = new Vector[n];
for (int i = 0; i < n; i++)
buckets[i] = new Vector<>();
// Add elements into different buckets
for (float value : arr) {
int index = (int) (value * n);
buckets[index].add(value);
}
// Sort individual buckets
for (Vector<Float> bucket : buckets)
Collections.sort(bucket);
// Concatenate all buckets into arr[]
int index = 0;
for (Vector<Float> bucket : buckets)
for (float value : bucket)
arr[index++] = value;
}
public static void main(String[] args) {
float[] data = {(float) 0.897, (float) 0.565, (float) 0.656,
(float) 0.123, (float) 0.665, (float) 0.343};
sort(data);
for (float num : data)
System.out.print(num + " ");
}
}