-
-
Notifications
You must be signed in to change notification settings - Fork 155
Expand file tree
/
Copy pathBucketSort.java
More file actions
72 lines (58 loc) · 1.76 KB
/
Copy pathBucketSort.java
File metadata and controls
72 lines (58 loc) · 1.76 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
69
70
71
72
package util;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
/**
* Created by nikoo28 on 1/1/21 1:16 AM
*/
public class BucketSort {
static void bucketSort(int[] arr, int noOfBuckets) {
boolean isNegativePresent = false;
int offset = Integer.MAX_VALUE;
for (int i : arr) {
if (i < offset) offset = i;
if (i < 0) isNegativePresent = true;
}
int globalMax = Integer.MIN_VALUE;
int globalMin = Integer.MAX_VALUE;
for (int i = 0; i < arr.length; i++) {
arr[i] -= offset;
globalMin = Math.min(arr[i], globalMin);
globalMax = Math.max(arr[i], globalMax);
}
int range = globalMax - globalMin;
int bucketRange = (int) Math.ceil((double) range / noOfBuckets);
// Create bucket array
List<Integer>[] buckets = new List[noOfBuckets];
// Associate a list with each index in the bucket array
for (int i = 0; i < noOfBuckets; i++) {
buckets[i] = new LinkedList<>();
}
// Assign numbers from array to the proper bucket
// by using hashing function
for (int num : arr) {
buckets[hash(num, bucketRange, noOfBuckets)].add(num);
}
// sort buckets
for (List<Integer> bucket : buckets) Collections.sort(bucket);
int idx = 0;
// Merge buckets to get sorted array
for (List<Integer> bucket : buckets) {
for (int num : bucket) {
arr[idx++] = num;
}
}
if (isNegativePresent) {
for (int i = 0; i < arr.length; i++) {
arr[i] += offset;
}
}
}
// A very simple hash function
private static int hash(int num, int hashValue, int numberOfBuckets) {
int bucketNumber = num / hashValue;
if (bucketNumber == numberOfBuckets)
bucketNumber--;
return bucketNumber;
}
}