Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit dc92687

Browse files
committed
Bucket Sort added
1 parent 6497e77 commit dc92687

File tree

1 file changed

+66
-0
lines changed

1 file changed

+66
-0
lines changed

‎AlgorithmCode/Sorting/BucketSort.java

Lines changed: 66 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,66 @@
1+
/**
2+
* Bucket sort implementation
3+
*
4+
*
5+
* @author William Fiset, william.alexandre.fiset@gmail.com
6+
*/
7+
8+
package Sorting;
9+
10+
import java.util.*;
11+
12+
public class BucketSort{
13+
// Performs a bucket sort of an array in which all the elements are
14+
// bounded in the range [minValue, maxValue]. For bucket sort to give linear
15+
// performance the elements need to be uniformly distributed
16+
private static void bucketSort(int[] ar) {
17+
18+
if (ar == null || ar.length == 0) return;
19+
20+
int minValue = Integer.MAX_VALUE;
21+
int maxValue = Integer.MIN_VALUE;
22+
for (int i = 0; i < ar.length; i++) {
23+
if (ar[i] < minValue) minValue = ar[i];
24+
if (ar[i] > maxValue) maxValue = ar[i];
25+
}
26+
if (minValue == maxValue) return;
27+
28+
// N is number elements and M is the range of values
29+
final int N = ar.length, M = maxValue - minValue + 1, numBuckets = M / N + 1;
30+
List<List<Integer>> buckets = new ArrayList<>(numBuckets);
31+
for (int i = 0; i < numBuckets; i++) buckets.add(new ArrayList<>());
32+
33+
// Place each element in a bucket
34+
for (int i = 0; i < N; i++) {
35+
int bi = (ar[i] - minValue) / M;
36+
List<Integer> bucket = buckets.get(bi);
37+
bucket.add(ar[i]);
38+
}
39+
40+
// Sort buckets and stitch together answer
41+
for (int bi = 0, j = 0; bi < numBuckets; bi++) {
42+
List<Integer> bucket = buckets.get(bi);
43+
if (bucket != null) {
44+
Collections.sort(bucket);
45+
for (int k = 0; k < bucket.size(); k++) {
46+
ar[j++] = bucket.get(k);
47+
}
48+
}
49+
}
50+
}
51+
52+
public static void main(String[] args) {
53+
54+
int[] array = {10, 4, 6, 8, 13, 2, 3};
55+
BucketSort.bucketSort(array);
56+
// Prints:
57+
// [2, 3, 4, 6, 8, 10, 13]
58+
System.out.println(java.util.Arrays.toString(array));
59+
60+
array = new int[] {10, 10, 10, 10, 10};
61+
BucketSort.bucketSort(array);
62+
// Prints:
63+
// [10, 10, 10, 10, 10]
64+
System.out.println(java.util.Arrays.toString(array));
65+
}
66+
}

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /