Skip to content

Commit 6c75c85

Browse files
Radix Sorting Algo.java
1 parent f337214 commit 6c75c85

File tree

1 file changed

+65
-0
lines changed

1 file changed

+65
-0
lines changed

Radix Sorting Algo.java

+65
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,65 @@
1+
2+
import java.util.Arrays;
3+
4+
class RadixSort {
5+
6+
// Using counting sort to sort the elements in the basis of significant places
7+
void countingSort(int array[], int size, int place) {
8+
int[] output = new int[size + 1];
9+
int max = array[0];
10+
for (int i = 1; i < size; i++) {
11+
if (array[i] > max)
12+
max = array[i];
13+
}
14+
int[] count = new int[max + 1];
15+
16+
for (int i = 0; i < max; ++i)
17+
count[i] = 0;
18+
19+
// Calculate count of elements
20+
for (int i = 0; i < size; i++)
21+
count[(array[i] / place) % 10]++;
22+
23+
// Calculate cumulative count
24+
for (int i = 1; i < 10; i++)
25+
count[i] += count[i - 1];
26+
27+
// Place the elements in sorted order
28+
for (int i = size - 1; i >= 0; i--) {
29+
output[count[(array[i] / place) % 10] - 1] = array[i];
30+
count[(array[i] / place) % 10]--;
31+
}
32+
33+
for (int i = 0; i < size; i++)
34+
array[i] = output[i];
35+
}
36+
37+
// Function to get the largest element from an array
38+
int getMax(int array[], int n) {
39+
int max = array[0];
40+
for (int i = 1; i < n; i++)
41+
if (array[i] > max)
42+
max = array[i];
43+
return max;
44+
}
45+
46+
// Main function to implement radix sort
47+
void radixSort(int array[], int size) {
48+
// Get maximum element
49+
int max = getMax(array, size);
50+
51+
// Apply counting sort to sort elements based on place value.
52+
for (int place = 1; max / place > 0; place *= 10)
53+
countingSort(array, size, place);
54+
}
55+
56+
// Driver code
57+
public static void main(String args[]) {
58+
int[] data = { 121, 432, 564, 23, 1, 45, 788 };
59+
int size = data.length;
60+
RadixSort rs = new RadixSort();
61+
rs.radixSort(data, size);
62+
System.out.println("Sorted Array in Ascending Order: ");
63+
System.out.println(Arrays.toString(data));
64+
}
65+
}

0 commit comments

Comments
 (0)