C++ Program For Radix Sort
Last Updated :
25 Oct, 2023
Radix Sort is a sorting technique in which we sort the elements by processing each and every digit of that element. It is not a comparison-based sorting algorithm which means we do not compare the elements in a radix sort in order to sort them. Here, we apply counting sort to every digit of an element starting from the Least Significant Digit (LSB) to the Most Significant Digit (MSB) or vice versa.
Prerequisite: Counting Sort
Algorithm for Radix Sort in C++
The Radix Sort is based on the idea that by sorting the dataset on the basis of each decimal place, it will be eventually completely sorted. Radix sort uses the counting sort algorithm as the subroutine.
The algorithm of the radix sort can be written as:
arr[] = {a1, a2, a3 ... an};
for (each decimal place) {
countingSort(arr);
}
Working of Radix Sort in C++
We will understand the working of Radix Sort in C++ using an example.
Let's first take an array named 'original_arr' = {21, 300, 8, 92, 654, 100, 252, 333, 693, 18};
Original Array original-arr[]
Now, as the number of digits in the maximum element is 3 therefore we will represent all the elements of the array as 3-digit numbers.
Prefixing Required Zeroes to the Elements of Original ArrayPass 1
We take an array named 'count' whose size is 10 as the values will range from 0-9 always. Initially, we will initialize the count array with 0. Then we will update the count array with respect to the frequency of the digits. After that, we will perform prefix sum in the same way we do in a counting sort.
count Array in Pass 1
Now, we will find the final array after Pass 1 in the same way we did the counting sort. Let us name the final array as ans_arr.
Array after Radix Sort Pass 1For Pass 2
Now, we will take the ans_arr of Pass 1 as the original_arr for Pass 2 and continue the same steps of counting sort just like Pass 1. But with the difference we will consider the digits at second place.
Count Array in Pass 2
Array after Radix Sort Pass 2For Pass 3
Now, we will take the ans_arr of Pass 2 as the original_arr for Pass 3 and continue the same steps of counting sort just like Pass 1 and Pass 2 but again increase the place of the digits i.e. we will consider
Count Array in Pass 3
Array after Radix Sort Final Pass
The ans_arr that we get after Pass 3 is our final array after performing the Radix sort.
C++ Program for Radix Sort
C++
// C++ program to implement radix sort
#include <bits/stdc++.h>
using namespace std;
// counting sort implementation
void count_sort(int arr[], int n, int pos)
{
// we declare a count array and initialize the array by
// 0
int count[10] = { 0 };
// we count the frequency of each distinct digit at
// given place for every element in the original array
for (int i = 0; i < n; i++) {
count[(arr[i] / pos) % 10]++;
}
// we perform prefix sum and update the count array
for (int i = 1; i < 10; i++) {
count[i] = count[i] + count[i - 1];
}
// we store our answer in the ans array
int ans[n];
for (int i = n - 1; i >= 0; i--) {
ans[--count[(arr[i] / pos) % 10]] = arr[i];
}
// here we copy the contents of ans array to our
// original array
for (int i = 0; i < n; i++) {
arr[i] = ans[i];
}
}
// function to implement radix sort
void radix_sort(int arr[], int n)
{
// max_element() is a c++ stl function to find the
// maximum element from an array
int k = *max_element(arr, arr + n);
for (int pos = 1; (k / pos) > 0; pos *= 10) {
count_sort(arr, n, pos);
}
}
// driver code
int main()
{
int arr[] = { 6, 210, 300, 600, 1, 3 };
int n = sizeof(arr) / sizeof(arr[0]);
radix_sort(arr, n);
// displaying the result
cout << "Array after performing radix sort : " << endl;
for (int i = 0; i < n; i++) {
cout << arr[i] << " ";
}
return 0;
}
OutputArray after performing radix sort :
1 3 6 210 300 600
Complexity Analysis of Radix Sort
- Time Complexity of Radix Sort: O(d*(n + k)).
- Space Complexity of Radix Sort: O(n + k).
where d is the no. of digits, n is the total no. of elements and k is the base of the number system.
Benifits of Radix Sort
The radix sort has the following benefits:
- It is faster than other comparison-based sorting algorithms.
- It is a stable sort.
Limitations of Radix Sort:
The radix sort also has some limitations which are as follows:
- Radix sort is inefficient for sorting small data sets.
- Space Complexity is higher as compared to the other sorting algorithms.
- Processing negative numbers requires extra steps.
Similar Reads
C++ Program For Counting Sort
Counting Sort is a sorting technique in which the array is sorted according to the keys between some specific ranges. It is not a comparison sort because we do not sort the elements of the array by comparing them with other elements. In counting sort, we determine the position of each element in the
6 min read
C++ Program For Iterative Quick Sort
Quicksort also known as partition-exchange sort is a divide-and-conquer sorting algorithm that works by selecting a pivot element from the array and partitioning the other elements into two sub-arrays, according to whether they are less than or greater than the pivot element. The sub-arrays can then
4 min read
sort_heap function in C++
The sort_heap( ) is an STL algorithm which sorts a heap within the range specified by start and end. Sorts the elements in the heap range [start, end) into ascending order. The second form allows you to specify a comparison function that determines when one element is less than another. Defined in h
3 min read
std::partial_sort in C++
std::sort is used for sorting the elements present within a container. One of the variants of this is std::partial_sort , which is used for sorting not the entire range, but only a sub-part of it. It rearranges the elements in the range [first, last), in such a way that the elements before middle ar
7 min read
std::forward_list::sort() in C++ STL
Forward list in STL implements singly linked list. Introduced from C++11, forward list are useful than other containers in insertion, removal and moving operations (like sort) and allows time constant insertion and removal of elements.It differs from list by the fact that forward list keeps track of
3 min read
std::partial_sort_copy in C++
std::partial_sort is used for sorting the range within the entire container. So, if we want to keep the original container intact and just copy the sorted sub-part of the container into another one, then for that purpose, we can use std::partial_sort_copy. Just like std::partial_sort, partial_sort_c
4 min read
qsort() Function in C
The qsort() in C is a library function used to sort an array of items in ascending order or descending order. It stands for "quick sort," as it implements the quicksort algorithm for sorting which is one of the fastest and most efficient algorithms to sort the array. Let's take a look at an example
4 min read
Comparator Function of qsort() in C
In C, qsort() is used for sorting an array in desired order. But to provide compatibility to different data types, it additionally requires a comparator function to determine the order of how to arrange the elements. Let's take a look at an example: [GFGTABS] C #include <stdio.h> #include <
3 min read
C++ Comparison Operators
Comparison operators are operators used for comparing two elements, these are mostly used with if-else conditions as they return true-false as result. There are mainly 6 Comparison Operators namely: Greater than (>) : this operator checks whether operand1 is greater than operand2. If the result t
3 min read
Char Comparison in C
Char is a keyword used for representing characters in C. Character size in C is 1 byte. There are two methods to compare characters in C and these are: Using ASCII valuesUsing strcmp( ) .1. Using ASCII values to compare characters The first method is pretty simple, we all know that each character ca
3 min read