-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBucketSort.java
More file actions
52 lines (42 loc) · 1.33 KB
/
BucketSort.java
File metadata and controls
52 lines (42 loc) · 1.33 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
44
45
46
47
48
49
50
51
52
package Sorting;
import java.util.ArrayList;
import java.util.Collections;
/**
* Time Complexity: Worst & Average -O(N + K), Best - O(N), Auxiliary Space: O(N + K)
* It is "Stable Sort" as it does not change the order of the duplicate items.
* It is also "In Place".
*/
public class BucketSort {
static void bucketSort(float[] arr) {
int n = arr.length;
// Buckets
ArrayList<ArrayList<Float>> buckets = new ArrayList<>(n);
// Create empty buckets
for (int i = 0; i < n; i++) {
buckets.add(new ArrayList<>());
}
// Add elements into our buckets
for (float num : arr) {
int bucketIndex = (int) num * n;
buckets.get(bucketIndex).add(num);
}
// Sort each bucket individually
for (ArrayList<Float> bucket : buckets) {
Collections.sort(bucket);
}
// Merge all buckets to get final sorted array
int index = 0;
for (ArrayList<Float> currBucket : buckets) {
for (Float num : currBucket) {
arr[index++] = num;
}
}
}
public static void main(String[] args) {
float[] arr = {0.5f, 0.4f, 0.3f, 0.2f, 0.1f};
bucketSort(arr);
for (float val : arr) {
System.out.print(val + " ");
}
}
}