# Radix Sort Java Program and Algorithm

Here is a very basic and detailed description of algorithm that we follow to implement the radix sort in java. We mostly rely on the place value of digits to sort it out in the given list. So, our first basic task is to find out the number with maximum length and then iterate the whole loop over the length of the digit.

Next we arrange every number considering 1s place value, 10s place value, 100s place value and so on till the length of the maximum digit.

1. Find the length of the number that has maximum number of digits.
2. Initialize i=0, Repeat the below procedure till the length equals i.
3. Fill the bucket with all the digits in ith position.
4. Sort out the digits according to the order.
5. If length=i, i=i*10, goto to step 3. Else go to step 5
6. Print the sorted array.

### Complexity

The complexity of Radix Sort is far better than that of bubble sort and some other sorting techniques. It is as shown below depends on d and b.

O (d*(n+b))
d is digits in input integers.
b is the base for representing numbers.

### Explanation

Let us start the implementation of the program. First we define a class named RadixSort and obviously it has only one method named sort to sort the numbers given. This function is the central part of discussion and as always, we take the inputs for the user using the main function and pass it on to the sorting function. The below code snippet shows it.

You can observe that the function that we are going to implement doesn’t return anything as its return type is void. It takes in an unsorted array of numbers and sorts it. Now we will have a look at the algorithm to implement the sort function. The algorithm says we need to first find the number of digits in the longest number.

Using the above for loop we can find the maximum of all the numbers. Instead of finding its length we will iterate a while loop until the maximum number falls below zero by dividing the number by 10 for every iteration. Then sort the array using a temporary bucket and array b[ ] and place back the final contents.

Output

Enter number of integer elements
6

Enter 6 integer elements
12 9 15 4 0 1

Elements after sorting
0 1 4 9 12 15

Comment below if you have queries or found anything incorrect in above radix sort java program and algorithm.

### You May Also Like:

Category: Java Array A crazy computer and programming lover. He spend most of his time in programming, blogging and helping other programming geeks.

## 6 thoughts on “Radix Sort Java Program and Algorithm”

1. Orrin

int[] b = new int; Is in correct. b should be initialized to size n. It would cause a crash if a is larger than 10 as is.

1. Jessica Melissa Elano

yes b must take the value ‘a.length’

2. Anonymous

Your program crashes when I have negative numbers in my array.

3. Bharat Aneja

4. no1
1. Neeraj Mishra Post author