Java Program for Radix Sort

Java 8Server Side ProgrammingProgramming

Radix sort is a sorting technique that sorts the elements based on every digit in every element (or number). Based on the ones place digit (which is also known as least significant digit) and tens place digit (which is also known as most significant digit), hundreds place digit, and so on, the elements are sorted.

Example

Following is an example for Radix Sort in Java −

 Live Demo

import java.util.*;
public class my_radix_sorting {
   static int get_max_val(int my_arr[], int arr_len) {
      int max_val = my_arr[0];
      for (int i = 1; i < arr_len; i++)
         if (my_arr[i] > max_val)
         max_val = my_arr[i];
      return max_val;
   }
   static void countSort(int my_arr[], int arr_len, int exp) {
      int result[] = new int[arr_len];
      int i;
      int count[] = new int[10];
      Arrays.fill(count,0);
      for (i = 0; i < arr_len; i++)
         count[ (my_arr[i]/exp)%10 ]++;
      for (i = 1; i < 10; i++)
         count[i] += count[i - 1];
      for (i = arr_len - 1; i >= 0; i--) {
         result[count[ (my_arr[i]/exp)%10 ] - 1] = my_arr[i];
         count[ (my_arr[i]/exp)%10 ]--;
      }
      for (i = 0; i < arr_len; i++)
         my_arr[i] = result[i];
   }
   static void radix_sort(int my_arr[], int arr_len) {
      int m = get_max_val(my_arr, arr_len);
      for (int exp = 1; m/exp > 0; exp *= 10)
      countSort(my_arr, arr_len, exp);
   }
   public static void main (String[] args) {
      int my_arr[] = {56, 78, 102, 345, 67, 90, 102, 45, 78};
      int arr_len = my_arr.length;
      System.out.println("The array after performing radix sort is ");
      radix_sort(my_arr, arr_len);
      for (int i=0; i<arr_len; i++)
      System.out.print(my_arr[i]+" ");
   }
}

Output

The array after performing radix sort is
45 56 67 78 78 90 102 102 345

Explanation

In radix sort, every element is sorted based on its digit, wherein the least significant digit in every element is sorted first, and the most significant digit is sorted in the end. It uses counting sort as a sub-function to perform its sorting functions.

Given an array of elements, the first step is that the elements are sorted based on the least significant place’s digit, i.e ones place. Next the elements in the array are sorted based on tens place digits. Then, the elements are sorted based on hundreds place digit and so on. This is done with the help of ‘get_max_val’ function. In the main function, the array is defined, and the array is passed as a parameter to the ‘radix_sort’ function.

raja
Published on 14-Sep-2020 08:21:15
Advertisements