-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathRadixSort.java
More file actions
65 lines (55 loc) · 1.81 KB
/
RadixSort.java
File metadata and controls
65 lines (55 loc) · 1.81 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 Sorting;
/**
* 1) Digit by digit sorting or place by place.
* Time Complexity: Worst & Average - O(N * d), Best - O(N), Auxiliary Space: O(N)
* When all elements have the same number of digits, best case time complexity.
* It is "Stable Sort" as it does not change the order of the duplicate items.
* It is also "In Place".
*/
public class RadixSort {
// Finding the Max Element.
static int findMax(int[] arr) {
int mx = Integer.MIN_VALUE;
for (int num : arr) {
if (num > mx) mx = num;
}
return mx;
}
// Count Sort for Radix implementation.
static void countSort(int[] arr, int place) {
int n = arr.length;
int[] output = new int[n];
// Make frequency array
int[] count = new int[10];
for (int num : arr) {
count[(num / place) % 10]++;
}
// Make prefix sum array of count array
for (int i = 1; i < count.length; i++) {
count[i] += count[i - 1];
}
// Find the index of each element in the original array and put it in output, To Make Stable.
for (int i = n - 1; i >= 0; i--) {
int idx = count[(arr[i] / place) % 10] - 1;
output[idx] = arr[i];
count[(arr[i] / place) % 10]--;
}
// Copy all elements of output to array.
System.arraycopy(output, 0, arr, 0, n);
}
// Radix Sort
static void radixSort(int[] arr) {
int max = findMax(arr);
for (int place = 1; max / place > 0; place *= 10) {
countSort(arr, place);
}
}
public static void main(String[] args) {
int[] arr = {43, 453, 626, 894, 0, 3};
radixSort(arr);
for (int val : arr) {
System.out.print(val + " ");
}
System.out.println();
}
}