Radix Sort is a linear sorting algorithm (for fixed length digit counts) that sorts elements by processing them digit by digit. It is an efficient sorting algorithm for integers or strings with fixed-size keys.
It repeatedly distributes the elements into buckets based on each digit's value. This is different from other algorithms like Merge Sort or Quick Sort where we compare elements directly.
By repeatedly sorting the elements by their significant digits, from the least significant to the most significant, it achieves the final sorted order.
We use a stable algorithm like Counting Sort to sort the individual digits so that the overall algorithm remains stable.
To perform radix sort on the array [170, 45, 75, 90, 802, 24, 2, 66], we follow these steps:
Step 1: Find the largest element, which is 802. It has three digits, so we will iterate three times.
Step 2: Sort the elements based on the unit place digits (X=0).
How does Radix Sort Algorithm work | Step 2
Step 3: Sort the elements based on the tens place digits.
How does Radix Sort Algorithm work | Step 3
Step 4: Sort the elements based on the hundreds place digits.
How does Radix Sort Algorithm work | Step 4
Step 5: The array is now sorted in ascending order.
Below is the implementation for the above illustrations:
C++
// C++ implementation of Radix Sort#include<iostream>usingnamespacestd;// A utility function to get maximum// value in arr[]intgetMax(intarr[],intn){intmx=arr[0];for(inti=1;i<n;i++)if(arr[i]>mx)mx=arr[i];returnmx;}// A function to do counting sort of arr[]// according to the digit// represented by exp.voidcountSort(intarr[],intn,intexp){// Output arrayintoutput[n];inti,count[10]={0};// Store count of occurrences// in count[]for(i=0;i<n;i++)count[(arr[i]/exp)%10]++;// Change count[i] so that count[i]// now contains actual position// of this digit in output[]for(i=1;i<10;i++)count[i]+=count[i-1];// Build the output arrayfor(i=n-1;i>=0;i--){output[count[(arr[i]/exp)%10]-1]=arr[i];count[(arr[i]/exp)%10]--;}// Copy the output array to arr[],// so that arr[] now contains sorted// numbers according to current digitfor(i=0;i<n;i++)arr[i]=output[i];}// The main function to that sorts arr[]// of size n using Radix Sortvoidradixsort(intarr[],intn){// Find the maximum number to// know number of digitsintm=getMax(arr,n);// Do counting sort for every digit.// Note that instead of passing digit// number, exp is passed. exp is 10^i// where i is current digit numberfor(intexp=1;m/exp>0;exp*=10)countSort(arr,n,exp);}// A utility function to print an arrayvoidprint(intarr[],intn){for(inti=0;i<n;i++)cout<<arr[i]<<" ";}// Driver Codeintmain(){intarr[]={170,45,75,90,802,24,2,66};intn=sizeof(arr)/sizeof(arr[0]);// Function Callradixsort(arr,n);print(arr,n);return0;}
C
#include<stdio.h>// A utility function to get the maximum // value in arr[]intgetMax(intarr[],intn){intmx=arr[0];for(inti=1;i<n;i++)if(arr[i]>mx)mx=arr[i];returnmx;}// A function to do counting sort of arr[] // according to the digit represented by expvoidcountSort(intarr[],intn,intexp){intoutput[n];// Output arrayintcount[10]={0};// Initialize count array as 0// Store count of occurrences in count[]for(inti=0;i<n;i++)count[(arr[i]/exp)%10]++;// Change count[i] so that count[i] now // contains actual position of this digit// in output[]for(inti=1;i<10;i++)count[i]+=count[i-1];// Build the output arrayfor(inti=n-1;i>=0;i--){output[count[(arr[i]/exp)%10]-1]=arr[i];count[(arr[i]/exp)%10]--;}// Copy the output array to arr[], // so that arr[] now contains sorted // numbers according to current digitfor(inti=0;i<n;i++)arr[i]=output[i];}// The main function to sort arr[] of size // n using Radix SortvoidradixSort(intarr[],intn){// Find the maximum number to know // the number of digitsintm=getMax(arr,n);// Do counting sort for every digit// exp is 10^i where i is the current // digit numberfor(intexp=1;m/exp>0;exp*=10)countSort(arr,n,exp);}// A utility function to print an arrayvoidprintArray(intarr[],intn){for(inti=0;i<n;i++)printf("%d ",arr[i]);printf("\n");}// Driver codeintmain(){intarr[]={170,45,75,90,802,24,2,66};intn=sizeof(arr)/sizeof(arr[0]);// Function callradixSort(arr,n);printArray(arr,n);return0;}
Java
// Radix sort Java implementationimportjava.io.*;importjava.util.*;classRadix{// A utility function to get maximum value in arr[]staticintgetMax(intarr[],intn){intmx=arr[0];for(inti=1;i<n;i++)if(arr[i]>mx)mx=arr[i];returnmx;}// A function to do counting sort of arr[] according to// the digit represented by exp.staticvoidcountSort(intarr[],intn,intexp){intoutput[]=newint[n];// output arrayinti;intcount[]=newint[10];Arrays.fill(count,0);// Store count of occurrences in count[]for(i=0;i<n;i++)count[(arr[i]/exp)%10]++;// Change count[i] so that count[i] now contains// actual position of this digit in output[]for(i=1;i<10;i++)count[i]+=count[i-1];// Build the output arrayfor(i=n-1;i>=0;i--){output[count[(arr[i]/exp)%10]-1]=arr[i];count[(arr[i]/exp)%10]--;}// Copy the output array to arr[], so that arr[] now// contains sorted numbers according to current// digitfor(i=0;i<n;i++)arr[i]=output[i];}// The main function to that sorts arr[] of// size n using Radix Sortstaticvoidradixsort(intarr[],intn){// Find the maximum number to know number of digitsintm=getMax(arr,n);// Do counting sort for every digit. Note that// instead of passing digit number, exp is passed.// exp is 10^i where i is current digit numberfor(intexp=1;m/exp>0;exp*=10)countSort(arr,n,exp);}// A utility function to print an arraystaticvoidprint(intarr[],intn){for(inti=0;i<n;i++)System.out.print(arr[i]+" ");}// Main driver methodpublicstaticvoidmain(String[]args){intarr[]={170,45,75,90,802,24,2,66};intn=arr.length;// Function Callradixsort(arr,n);print(arr,n);}}
Python
# Python program for implementation of Radix Sort# A function to do counting sort of arr[] according to# the digit represented by exp.defcountingSort(arr,exp1):n=len(arr)# The output array elements that will have sorted arroutput=[0]*(n)# initialize count array as 0count=[0]*(10)# Store count of occurrences in count[]foriinrange(0,n):index=arr[i]//exp1count[index%10]+=1# Change count[i] so that count[i] now contains actual# position of this digit in output arrayforiinrange(1,10):count[i]+=count[i-1]# Build the output arrayi=n-1whilei>=0:index=arr[i]//exp1output[count[index%10]-1]=arr[i]count[index%10]-=1i-=1# Copying the output array to arr[],# so that arr now contains sorted numbersi=0foriinrange(0,len(arr)):arr[i]=output[i]# Method to do Radix SortdefradixSort(arr):# Find the maximum number to know number of digitsmax1=max(arr)# Do counting sort for every digit. Note that instead# of passing digit number, exp is passed. exp is 10^i# where i is current digit numberexp=1whilemax1/exp>=1:countingSort(arr,exp)exp*=10# Driver codearr=[170,45,75,90,802,24,2,66]# Function CallradixSort(arr)foriinrange(len(arr)):print(arr[i],end=" ")# This code is contributed by Mohit Kumra# Edited by Patrick Gallagher
C#
// C# implementation of Radix SortusingSystem;classGFG{publicstaticintgetMax(int[]arr,intn){intmx=arr[0];for(inti=1;i<n;i++)if(arr[i]>mx)mx=arr[i];returnmx;}// A function to do counting sort of arr[] according to// the digit represented by exp.publicstaticvoidcountSort(int[]arr,intn,intexp){int[]output=newint[n];// output arrayinti;int[]count=newint[10];// initializing all elements of count to 0for(i=0;i<10;i++)count[i]=0;// Store count of occurrences in count[]for(i=0;i<n;i++)count[(arr[i]/exp)%10]++;// Change count[i] so that count[i] now contains// actual// position of this digit in output[]for(i=1;i<10;i++)count[i]+=count[i-1];// Build the output arrayfor(i=n-1;i>=0;i--){output[count[(arr[i]/exp)%10]-1]=arr[i];count[(arr[i]/exp)%10]--;}// Copy the output array to arr[], so that arr[] now// contains sorted numbers according to current// digitfor(i=0;i<n;i++)arr[i]=output[i];}// The main function to that sorts arr[] of size n using// Radix Sortpublicstaticvoidradixsort(int[]arr,intn){// Find the maximum number to know number of digitsintm=getMax(arr,n);// Do counting sort for every digit. Note that// instead of passing digit number, exp is passed.// exp is 10^i where i is current digit numberfor(intexp=1;m/exp>0;exp*=10)countSort(arr,n,exp);}// A utility function to print an arraypublicstaticvoidprint(int[]arr,intn){for(inti=0;i<n;i++)Console.Write(arr[i]+" ");}// Driver CodepublicstaticvoidMain(){int[]arr={170,45,75,90,802,24,2,66};intn=arr.Length;// Function Callradixsort(arr,n);print(arr,n);}// This code is contributed by DrRoot_}
JavaScript
// Radix sort JavaScript implementation"use strict";// A utility function to get maximum value in arr[]functiongetMax(arr){constlength=arr.length;letmx=arr[0];for(leti=1;i<length;i++){if(arr[i]>mx)mx=arr[i];}returnmx;}// A function to do counting sort of arr[] according to// the digit represented by exp.functioncountSort(arr,exp){constlength=arr.length;letoutput=Array(length);// output arrayletcount=Array(10).fill(0,0);// Store count of occurrences in count[]for(leti=0;i<length;i++){constdigit=Math.floor(arr[i]/exp)%10;count[digit]++;}// Change count[i] so that count[i] now contains// actual position of this digit in output[]for(leti=1;i<10;i++){count[i]+=count[i-1];}// Build the output arrayfor(leti=length-1;i>=0;i--){constdigit=Math.floor(arr[i]/exp)%10;output[count[digit]-1]=arr[i];count[digit]--;}returnoutput;}// The main function to that sorts arr[] using Radix SortfunctionradixSort(arr){// Find the maximum number to know number of digitsconstmaxNumber=getMax(arr);// Create a shallow copy where the sorted values will be keptletsortedArr=[...arr];// Do counting sort for every digit. Note that// instead of passing digit number, exp is passed.// exp is 10^i where i is current digit numberfor(letexp=1;Math.floor(maxNumber/exp)>0;exp*=10){// Get the Count sort iterationconstsortedIteration=countSort(sortedArr,exp);sortedArr=sortedIteration;}returnsortedArr;}/*Driver Code*/constarr=[170,45,75,90,802,24,2,66];// Function CallconstsortedArr=radixSort(arr);console.log(sortedArr.join(" "));// This code is contributed by beeduhboodee
PHP
<?php// PHP implementation of Radix Sort // A function to do counting sort of arr[] // according to the digit represented by exp. functioncountSort(&$arr,$n,$exp){$output=array_fill(0,$n,0);// output array $count=array_fill(0,10,0);// Store count of occurrences in count[] for($i=0;$i<$n;$i++)$count[($arr[$i]/$exp)%10]++;// Change count[i] so that count[i] // now contains actual position of // this digit in output[] for($i=1;$i<10;$i++)$count[$i]+=$count[$i-1];// Build the output array for($i=$n-1;$i>=0;$i--){$output[$count[($arr[$i]/$exp)%10]-1]=$arr[$i];$count[($arr[$i]/$exp)%10]--;}// Copy the output array to arr[], so // that arr[] now contains sorted numbers// according to current digit for($i=0;$i<$n;$i++)$arr[$i]=$output[$i];}// The main function to that sorts arr[] // of size n using Radix Sort functionradixsort(&$arr,$n){// Find the maximum number to know// number of digits $m=max($arr);// Do counting sort for every digit. Note // that instead of passing digit number, // exp is passed. exp is 10^i where i is // current digit number for($exp=1;$m/$exp>0;$exp*=10)countSort($arr,$n,$exp);}// A utility function to print an array functionPrintArray(&$arr,$n){for($i=0;$i<$n;$i++)echo$arr[$i]." ";}// Driver Code $arr=array(170,45,75,90,802,24,2,66);$n=count($arr);// Function Callradixsort($arr,$n);PrintArray($arr,$n);// This code is contributed by rathbhupendra?>
Dart
// Radix sort Dart implementation/// A utility function to get the maximum value of a `List<int>` [array]intgetMax(List<int>array){intmax=array[0];for(finalitinarray){if(it>max){max=it;}}returnmax;}/// A function to do counting sort of `List<int>` [array] according to the/// digit represented by [exp].List<int>countSort(List<int>array,intexp){finallength=array.length;finaloutputArr=List.filled(length,0);// A list where index represents the digit and value represents the count of// occurrencesfinaldigitsCount=List.filled(10,0);// Store count of occurrences in digitsCount[]for(finaliteminarray){finaldigit=item~/exp%10;digitsCount[digit]++;}// Change digitsCount[i] so that digitsCount[i] now contains actual position// of this digit in outputArr[]for(inti=1;i<10;i++){digitsCount[i]+=digitsCount[i-1];}// Build the output arrayfor(inti=length-1;i>=0;i--){finalitem=array[i];finaldigit=item~/exp%10;outputArr[digitsCount[digit]-1]=item;digitsCount[digit]--;}returnoutputArr;}/// The main function to that sorts a `List<int>` [array] using Radix sortList<int>radixSort(List<int>array){// Find the maximum number to know number of digitsfinalmaxNumber=getMax(array);// Shallow copy of the input arrayfinalsortedArr=List.of(array);// Do counting sort for every digit. Note that instead of passing digit// number, exp is passed. exp is 10^i, where i is current digit numberfor(intexp=1;maxNumber~/exp>0;exp*=10){finalsortedIteration=countSort(sortedArr,exp);sortedArr.clear();sortedArr.addAll(sortedIteration);}returnsortedArr;}voidmain(){constarray=[170,45,75,90,802,24,2,66];finalsortedArray=radixSort(array);print(sortedArray);}// This code is contributed by beeduhboodee
Output
2 24 45 66 75 90 170 802
Complexity Analysis of Radix Sort:
Time Complexity:
Radix sort is a non-comparative integer sorting algorithm that sorts data with integer keys by grouping the keys by the individual digits which share the same significant position and value. It has a time complexity of O(d * (n + b)), where d is the number of digits, n is the number of elements, and b is the base of the number system being used.
In practical implementations, radix sort is often faster than other comparison-based sorting algorithms, such as quicksort or merge sort, for large datasets, especially when the keys have many digits. However, its time complexity grows linearly with the number of digits, and so it is not as efficient for small datasets.
Auxiliary Space:
Radix sort also has a space complexity of O(n + b), where n is the number of elements and b is the base of the number system. This space complexity comes from the need to create buckets for each digit value and to copy the elements back to the original array after each digit has been sorted.