Skip to content

Commit ae8b97d

Browse files
committed
Radix Sort
1 parent e7a19e6 commit ae8b97d

File tree

1 file changed

+48
-0
lines changed

1 file changed

+48
-0
lines changed

java/sorting/radix-sort.java

Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
import java.io.*;
2+
import java.util.*;
3+
4+
class Radix {
5+
static int getMax(int arr[], int n)
6+
{
7+
int mx = arr[0];
8+
for (int i = 1; i < n; i++)
9+
if (arr[i] > mx)
10+
mx = arr[i];
11+
return mx;
12+
}
13+
static void countSort(int arr[], int n, int exp)
14+
{
15+
int output[] = new int[n];
16+
int i;
17+
int count[] = new int[10];
18+
Arrays.fill(count, 0);
19+
for (i = 0; i < n; i++)
20+
count[(arr[i] / exp) % 10]++;
21+
for (i = 1; i < 10; i++)
22+
count[i] += count[i - 1];
23+
for (i = n - 1; i >= 0; i--) {
24+
output[count[(arr[i] / exp) % 10] - 1] = arr[i];
25+
count[(arr[i] / exp) % 10]--;
26+
}
27+
for (i = 0; i < n; i++)
28+
arr[i] = output[i];
29+
}
30+
static void radixsort(int arr[], int n)
31+
{
32+
int m = getMax(arr, n);
33+
for (int exp = 1; m / exp > 0; exp *= 10)
34+
countSort(arr, n, exp);
35+
}
36+
static void print(int arr[], int n)
37+
{
38+
for (int i = 0; i < n; i++)
39+
System.out.print(arr[i] + " ");
40+
}
41+
public static void main(String[] args)
42+
{
43+
int arr[] = { 170, 45, 75, 90, 802, 24, 2, 66 };
44+
int n = arr.length;
45+
radixsort(arr, n);
46+
print(arr, n);
47+
}
48+
}

0 commit comments

Comments
 (0)