forked from janbodnar/Java-Advanced
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathArrayBucketSortEx.java
More file actions
62 lines (43 loc) · 1.52 KB
/
ArrayBucketSortEx.java
File metadata and controls
62 lines (43 loc) · 1.52 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
package com.zetcode;
import java.util.Arrays;
// Sorting positive integers with Bucket (non-comparison) sort algorithm
public class ArrayBucketSortEx {
static int[] doBucketSort(int[] vals, int max) {
// creates empty bucket and sorted array objects
int[] bucket = new int[max + 1];
int[] sorted_vals = new int[vals.length];
// each value is an index in the bucket having value 1
// if there are same values, the index is incremented
for (int i = 0; i < vals.length; i++) {
bucket[vals[i]]++;
}
int outPos = 0;
// the bucket elements with non zero values are added
// to the sorted_values array
for (int i = 0; i < bucket.length; i++) {
for (int j = 0; j < bucket[i]; j++) {
sorted_vals[outPos++] = i;
}
}
return sorted_vals;
}
// calculates max value
static int max(int[] vals) {
int max = 0;
for (int i = 0; i < vals.length; i++) {
if (vals[i] > max) {
max = vals[i];
}
}
return max;
}
public static void main(String args[]) {
int[] rnums = {3, 2, 2, 1, 16, 7, 12, 1, 7, 0, 23};
int maxValue = max(rnums);
System.out.println("Original array: ");
System.out.println(Arrays.toString(rnums));
System.out.println("Sorted array: ");
int[] sorted = doBucketSort(rnums, maxValue);
System.out.println(Arrays.toString(sorted));
}
}