## Friday, February 1, 2019

### Radix Sort Program in Java

In this post we’ll see how to write Radix sort program in Java. Radix sort is in the league of Counting Sort and Bucket Sort which are O(n) sorting algorithms.

### How does Radix sort work

Radix sort works by doing the sorting in passes moving from least significant digit to most significant digit. In each pass you can use any stable sort to sort the numbers on the digit.

If you have an array Arr with the maximum element in array Arr having number of digits as d, then the working of Radix sort is as shown below.

```for i = 1 to d
Use any stable sort (like counting sort)
to sort Arr on digit d
```

Following image shows how Radix sort sorts an input array in each pass. Here the maximum number is 655 so number of passes is 3.

Java program for Radix sort works on the following logic.

1. Find the maximum number in the input array.
2. Loop to iterate each digit of the maximum number starting from the least significant digit.
3. Sort the array on that digit using Counting sort.
```public class RadixSort {

public static void main(String[] args) {
int[] arr = {80, 406, 21, 655, 55, 4, 8, 91, 87, 6};
System.out.println("Original Array- " + Arrays.toString(arr));
System.out.println("Sorted array after Radix sort- " + Arrays.toString(arr));
}

int max = getMaxElement(arr);
int position = 1;
while(max/position > 0){
countingSort(arr, position);
position *= 10;
}
}

private static int getMaxElement(int[] arr){
int max = arr;
for(int i = 1; i < arr.length; i++){
if (arr[i] > max){
max = arr[i];
}
}
return max;
}

private static void countingSort(int[] arr, int position){
int n = arr.length;
int[] output = new int[n];
int[] count = new int[n];

//count number of times each element appear
for(int i = 0; i < arr.length; i++){
count[(arr[i]/position)%10]++;
}

// each element stores (element at current index+element
// at previous index) to get the actual position of the element
for(int i = 1; i < n; i++){
count[i] = count[i] + count[i-1];
}

// for correct placement of the numbers start from the end
for(int i = n-1; i >=0; i--){
output[count[(arr[i]/position)%10] - 1] = arr[i];
count[(arr[i]/position)%10]--;
}
// Copy output array to input to the input for
// the next stage of counting sort
for(int i = 0; i < output.length; i++){
arr[i] = output[i];
}
System.out.println("Counting sort at this stage " + Arrays.toString(arr));
}
}
```

Output

```Original Array- [80, 406, 21, 655, 55, 4, 8, 91, 87, 6]
Counting sort at this stage [80, 21, 91, 4, 655, 55, 406, 6, 87, 8]
Counting sort at this stage [4, 406, 6, 8, 21, 655, 55, 80, 87, 91]
Counting sort at this stage [4, 6, 8, 21, 55, 80, 87, 91, 406, 655]
Sorted array after Radix sort- [4, 6, 8, 21, 55, 80, 87, 91, 406, 655]
```