Skip to content

Commit 39a39fa

Browse files
Merge pull request codemistic#580 from s-a-c-h-i-n/main
Radix sort implementation in java
2 parents 9da3f02 + adbeea9 commit 39a39fa

File tree

1 file changed

+80
-0
lines changed

1 file changed

+80
-0
lines changed

Java/RadixSort.java

Lines changed: 80 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,80 @@
1+
// Radix sort Java implementation
2+
3+
import java.io.*;
4+
import java.util.*;
5+
6+
class Radix {
7+
8+
// A utility function to get maximum value in arr[]
9+
static int getMax(int arr[], int n)
10+
{
11+
int mx = arr[0];
12+
for (int i = 1; i < n; i++)
13+
if (arr[i] > mx)
14+
mx = arr[i];
15+
return mx;
16+
}
17+
18+
// A function to do counting sort of arr[] according to
19+
// the digit represented by exp.
20+
static void countSort(int arr[], int n, int exp)
21+
{
22+
int output[] = new int[n]; // output array
23+
int i;
24+
int count[] = new int[10];
25+
Arrays.fill(count, 0);
26+
27+
// Store count of occurrences in count[]
28+
for (i = 0; i < n; i++)
29+
count[(arr[i] / exp) % 10]++;
30+
31+
// Change count[i] so that count[i] now contains
32+
// actual position of this digit in output[]
33+
for (i = 1; i < 10; i++)
34+
count[i] += count[i - 1];
35+
36+
// Build the output array
37+
for (i = n - 1; i >= 0; i--) {
38+
output[count[(arr[i] / exp) % 10] - 1] = arr[i];
39+
count[(arr[i] / exp) % 10]--;
40+
}
41+
42+
// Copy the output array to arr[], so that arr[] now
43+
// contains sorted numbers according to current
44+
// digit
45+
for (i = 0; i < n; i++)
46+
arr[i] = output[i];
47+
}
48+
49+
// The main function to that sorts arr[] of
50+
// size n using Radix Sort
51+
static void radixsort(int arr[], int n)
52+
{
53+
// Find the maximum number to know number of digits
54+
int m = getMax(arr, n);
55+
56+
// Do counting sort for every digit. Note that
57+
// instead of passing digit number, exp is passed.
58+
// exp is 10^i where i is current digit number
59+
for (int exp = 1; m / exp > 0; exp *= 10)
60+
countSort(arr, n, exp);
61+
}
62+
63+
// A utility function to print an array
64+
static void print(int arr[], int n)
65+
{
66+
for (int i = 0; i < n; i++)
67+
System.out.print(arr[i] + " ");
68+
}
69+
70+
// Main driver method
71+
public static void main(String[] args)
72+
{
73+
int arr[] = { 170, 45, 75, 90, 802, 24, 2, 66 };
74+
int n = arr.length;
75+
76+
// Function Call
77+
radixsort(arr, n);
78+
print(arr, n);
79+
}
80+
}

0 commit comments

Comments
 (0)