Repository navigation
Expand file tree
/
Copy pathBucketSort_Java.java
More file actions
68 lines (54 loc) · 1.85 KB
/
Copy pathBucketSort_Java.java
File metadata and controls
68 lines (54 loc) · 1.85 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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
import java.util.*;
public class BucketSort {
// Method to perform insertion sort on a bucket
public static void insertionSort(ArrayList<Float> bucket) {
for (int i = 1; i < bucket.size(); i++) {
float key = bucket.get(i);
int j = i - 1;
while (j >= 0 && bucket.get(j) > key) {
bucket.set(j + 1, bucket.get(j));
j--;
}
bucket.set(j + 1, key);
}
}
public static void bucketSort(float[] arr) {
int n = arr.length;
// Create n buckets
ArrayList<Float>[] buckets = new ArrayList[n];
for (int i = 0; i < n; i++) {
buckets[i] = new ArrayList<>();
}
// Insert elements into their respective buckets
for (float value : arr) {
int index = (int) (value * n); // bucket index
buckets[index].add(value);
}
// Sort each bucket using insertion sort
for (int i = 0; i < n; i++) {
insertionSort(buckets[i]);
}
// Merge all buckets back into arr[]
int idx = 0;
for (int i = 0; i < n; i++) {
for (float value : buckets[i]) {
arr[idx++] = value;
}
}
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter number of elements: ");
int n = sc.nextInt();
float[] arr = new float[n];
System.out.println("Enter " + n + " floating values between 0 and 1:");
for (int i = 0; i < n; i++) {
arr[i] = sc.nextFloat();
}
bucketSort(arr);
System.out.println("\nSorted Array:");
for (float num : arr) {
System.out.print(num + " ");
}
}
}