forked from Manish57-droid/python
- Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbucket.java
More file actions
Latest commit
60 lines (49 loc) · 1.23 KB
/
Copy pathbucket.java
File metadata and controls
60 lines (49 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
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
// Java program to sort an array
// using bucket sort
importjava.util.*;
importjava.util.Collections;
classGFG {
// Function to sort arr[] of size n
// using bucket sort
staticvoidbucketSort(floatarr[], intn)
{
if (n <= 0)
return;
// 1) Create n empty buckets
@SuppressWarnings("unchecked")
Vector<Float>[] buckets = newVector[n];
for (inti = 0; i < n; i++) {
buckets[i] = newVector<Float>();
}
// 2) Put array elements in different buckets
for (inti = 0; i < n; i++) {
floatidx = arr[i] * n;
buckets[(int)idx].add(arr[i]);
}
// 3) Sort individual buckets
for (inti = 0; i < n; i++) {
Collections.sort(buckets[i]);
}
// 4) Concatenate all buckets into arr[]
intindex = 0;
for (inti = 0; i < n; i++) {
for (intj = 0; j < buckets[i].size(); j++) {
arr[index++] = buckets[i].get(j);
}
}
}
// Driver code
publicstaticvoidmain(Stringargs[])
{
floatarr[] = { (float)0.897, (float)0.565,
(float)0.656, (float)0.1234,
(float)0.665, (float)0.3434 };
intn = arr.length;
bucketSort(arr, n);
System.out.println("Sorted array is ");
for (floatel : arr) {
System.out.print(el + " ");
}
}
}
// This code is contributed by Himangshu Shekhar Jha