-
-
Notifications
You must be signed in to change notification settings - Fork 155
Expand file tree
/
Copy pathRadixSort.java
More file actions
65 lines (50 loc) · 1.4 KB
/
Copy pathRadixSort.java
File metadata and controls
65 lines (50 loc) · 1.4 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
package util;
import java.util.Arrays;
/**
* Created by nikoo28 on 1/14/21 1:16 AM
*/
public class RadixSort {
private void countingSort(int[] arr, int place) {
int size = arr.length;
int max = Arrays.stream(arr).max().getAsInt();
int[] output = new int[size + 1];
int[] count = new int[max + 1];
// Calculate count of elements
for (int j : arr)
count[(j / place) % 10]++;
// Calculate cumulative count
for (int i = 1; i < 10; i++)
count[i] += count[i - 1];
// Place the elements in sorted order
for (int i = size - 1; i >= 0; i--) {
output[count[(arr[i] / place) % 10] - 1] = arr[i];
count[(arr[i] / place) % 10]--;
}
System.arraycopy(output, 0, arr, 0, size);
}
// Main function to implement radix sort
void radixSort(int[] arr) {
boolean isNegative = false;
for (int i : arr) {
if (i < 0) {
isNegative = true;
break;
}
}
int min = 0;
if (isNegative) {
min = Arrays.stream(arr).min().getAsInt();
for (int i = 0; i < arr.length; i++) {
arr[i] -= min;
}
}
// Get maximum element
int max = Arrays.stream(arr).max().getAsInt();
// Apply counting sort to sort elements based on place value.
for (int place = 1; max / place > 0; place *= 10)
countingSort(arr, place);
for (int i = 0; i < arr.length; i++) {
arr[i] += min;
}
}
}