Skip to content

Commit dd6feb2

Browse files
Merge pull request #377 from prachie6157/main
Create Bucket sort.java
2 parents 140b0cc + f3de06e commit dd6feb2

File tree

1 file changed

+47
-0
lines changed

1 file changed

+47
-0
lines changed
Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
// Bucket sort in Java
2+
3+
import java.util.ArrayList;
4+
import java.util.Collections;
5+
6+
public class BucketSort {
7+
public void bucketSort(float[] arr, int n) {
8+
if (n <= 0)
9+
return;
10+
@SuppressWarnings("unchecked")
11+
ArrayList<Float>[] bucket = new ArrayList[n];
12+
13+
// Create empty buckets
14+
for (int i = 0; i < n; i++)
15+
bucket[i] = new ArrayList<Float>();
16+
17+
// Add elements into the buckets
18+
for (int i = 0; i < n; i++) {
19+
int bucketIndex = (int) arr[i] * n;
20+
bucket[bucketIndex].add(arr[i]);
21+
}
22+
23+
// Sort the elements of each bucket
24+
for (int i = 0; i < n; i++) {
25+
Collections.sort((bucket[i]));
26+
}
27+
28+
// Get the sorted array
29+
int index = 0;
30+
for (int i = 0; i < n; i++) {
31+
for (int j = 0, size = bucket[i].size(); j < size; j++) {
32+
arr[index++] = bucket[i].get(j);
33+
}
34+
}
35+
}
36+
37+
// Driver code
38+
public static void main(String[] args) {
39+
BucketSort b = new BucketSort();
40+
float[] arr = { (float) 0.42, (float) 0.32, (float) 0.33, (float) 0.52, (float) 0.37, (float) 0.47,
41+
(float) 0.51 };
42+
b.bucketSort(arr, 7);
43+
44+
for (float i : arr)
45+
System.out.print(i + " ");
46+
}
47+
}

0 commit comments

Comments
 (0)