-
Notifications
You must be signed in to change notification settings - Fork 27
/
bucketSort.java
59 lines (42 loc) · 1022 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
46
47
48
49
50
51
52
53
54
55
56
57
// Java program to sort an array
// using bucket sort
import java.util.*;
import java.util.Collections;
class Solution {
static void bucketSort(float arr[], int n)
{
if (n <= 0)
return;
// 1) Create n empty buckets
@SuppressWarnings("unchecked")
Vector<Float>[] buckets = new Vector[n];
for (int i = 0; i < n; i++) {
buckets[i] = new Vector<Float>();
}
for (int i = 0; i < n; i++) {
float idx = arr[i] * n;
buckets[(int)idx].add(arr[i]);
}
for (int i = 0; i < n; i++) {
Collections.sort(buckets[i]);
}
int index = 0;
for (int i = 0; i < n; i++) {
for (int j = 0; j < buckets[i].size(); j++) {
arr[index++] = buckets[i].get(j);
}
}
}
public static void main(String args[])
{
float arr[] = { (float)0.897, (float)0.565,
(float)0.656, (float)0.1234,
(float)0.665, (float)0.3434 };
int n = arr.length;
bucketSort(arr, n);
System.out.println("Sorted array is ");
for (float el : arr) {
System.out.print(el + " ");
}
}
}