Skip to content

Commit d76c180

Browse files
authored
Java Implementation of Radix Sort div-bargali#623
Java Implementation of Radix Sort
2 parents 333825c + 7eb5d76 commit d76c180

File tree

1 file changed

+75
-0
lines changed

1 file changed

+75
-0
lines changed
Lines changed: 75 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,75 @@
1+
//Radix Sort implementation
2+
import java.util.Scanner;
3+
import java.util.Arrays;
4+
5+
class Radix {
6+
7+
// An utility function to find the maximum element
8+
static int findMaxElement(int arr[], int n)
9+
{
10+
int mx = arr[0];
11+
for (int i = 1; i < n; i++)
12+
if (arr[i] > mx)
13+
mx = arr[i];
14+
return mx;
15+
}
16+
17+
static void countingSort(int arr[], int n, int exp)
18+
{
19+
int output[] = new int[n];
20+
int count[] = new int[10];
21+
int i;
22+
Arrays.fill(count, 0);
23+
24+
// Storing the count of all occurences
25+
for (i = 0; i < n; i++)
26+
count[(arr[i] / exp) % 10]++;
27+
28+
// Change count[i] so that count[i] now contains actual position of this digit in output[]
29+
for (i = 1; i < 10; i++)
30+
count[i] += count[i - 1];
31+
32+
// Building the output array
33+
for (i = n - 1; i >= 0; i--) {
34+
output[count[(arr[i] / exp) % 10] - 1] = arr[i];
35+
count[(arr[i] / exp) % 10]--;
36+
}
37+
38+
//Copying contents back to arr from output array
39+
for (i = 0; i < n; i++)
40+
arr[i] = output[i];
41+
}
42+
43+
//Performing Radix Sort
44+
static void radixsort(int arr[], int n)
45+
{
46+
// Finding the maximum number in the array to know the number of digits
47+
int m = findMaxElement(arr, n);
48+
49+
//Implementing Counting sort for each digit
50+
for (int exp = 1; m / exp > 0; exp *= 10)
51+
countingSort(arr, n, exp);
52+
}
53+
54+
//Driver Function
55+
public static void main(String[] args)
56+
{
57+
Scanner sc = new Scanner(System.in);
58+
59+
System.out.println("Enter the number of elements in the array - ");
60+
int n = sc.nextInt();
61+
62+
int arr[] = new int[n];
63+
64+
System.out.println("Enter array elements - ");
65+
for (int i = 0; i < n; i++)
66+
arr[i] = sc.nextInt();
67+
68+
radixsort(arr, n);
69+
70+
for (int i = 0; i < n; i++)
71+
System.out.print(arr[i] + " ");
72+
73+
sc.close();
74+
}
75+
}

0 commit comments

Comments
 (0)