-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathRadix Sort in Java
More file actions
66 lines (54 loc) · 2.04 KB
/
Radix Sort in Java
File metadata and controls
66 lines (54 loc) · 2.04 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
import java.util.Arrays;
public class RadixSort {
// Method to get the maximum value in the array
private static int getMax(int[] arr) {
int max = arr[0];
for (int i = 1; i < arr.length; i++) {
if (arr[i] > max) {
max = arr[i];
}
}
return max;
}
// Method to perform counting sort based on the digit represented by exp
private static void countingSort(int[] arr, int exp) {
int n = arr.length;
int[] output = new int[n]; // Output array
int[] count = new int[10]; // Count array to store occurrences of digits (0-9)
// Store count of occurrences of each digit
for (int i = 0; i < n; i++) {
int index = (arr[i] / exp) % 10;
count[index]++;
}
// Change count[i] so that it contains the actual position of this digit in output[]
for (int i = 1; i < 10; i++) {
count[i] += count[i - 1];
}
// Build the output array
for (int i = n - 1; i >= 0; i--) {
int index = (arr[i] / exp) % 10;
output[count[index] - 1] = arr[i];
count[index]--;
}
// Copy the sorted elements into the original array
System.arraycopy(output, 0, arr, 0, n);
}
// Method to perform radix sort
public static void radixSort(int[] arr) {
// Find the maximum number to determine the number of digits
int max = getMax(arr);
// Do counting sort for every digit. Note that instead of passing digit number,
// exp is passed. exp is 10^i where i is the current digit number
for (int exp = 1; max / exp > 0; exp *= 10) {
countingSort(arr, exp);
}
}
public static void main(String[] args) {
int[] arr = {170, 45, 75, 90, 802, 24, 2, 66};
System.out.println("Unsorted array:");
System.out.println(Arrays.toString(arr));
radixSort(arr);
System.out.println("Sorted array:");
System.out.println(Arrays.toString(arr));
}
}