forked from argonautica/sorting-algorithms
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBucketSort.java
More file actions
46 lines (39 loc) · 1.17 KB
/
BucketSort.java
File metadata and controls
46 lines (39 loc) · 1.17 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
public class BucketSort {
static int[] sort(int[] nums, int max) {
int[] bucket = new int[max + 1];
int[] sortedNums = new int[nums.length];
for (int i = 0; i < nums.length; i++) {
bucket[nums[i]]++;
}
int index = 0;
for (int i = 0; i < bucket.length; i++) {
for (int j = 0; j < bucket[i]; j++) {
sortedNums[index++] = i;
}
}
return sortedNums;
}
static int getMax(int[] nums) {
int max = 0;
for (int i = 0; i < nums.length; i++) {
if (nums[i] > max) {
max = nums[i];
}
}
return max;
}
public static void main(String args[]) {
int nums[] = {7, 3, 2, 1, 0, 4, 5};
int maxValue = getMax(nums);
System.out.println("Unsorted Array:");
for (int i = 0; i < nums.length; i++) {
System.out.print(nums[i] + " ");
}
nums = sort(nums, maxValue);
System.out.println();
System.out.println("Sorted Array:");
for (int i = 0; i < nums.length; i++) {
System.out.print(nums[i] + " ");
}
}
}