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 Bitonic Sort Bitonic Sequence: A sequence is called Bitonic if it is first increasing, then decreasing. In other words, an array arr[0..n-i] is Bitonic if there exists an index i where 0<=i<=n-1 such that x0 <= x1 â¦..<= xi and xi >= xi+1â¦.. >= xn-1 A sequence, sorted in increasing order is cons
4 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
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
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 t
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:C#include <stdio.h> #include <stdlib.h>
3 min read
sort() in C++ STL In C++, sort() is a built-in function used to sort the given range in desired order. It provides a simple and efficient way to sort the data in C++, but it only works on data structures that provide random access to its elements such as vectors and arrays.Let's take a look at an example:C++#include
4 min read
std::list::sort in C++ STL Lists are containers used in C++ to store data in a non contiguous fashion, Normally, Arrays and Vectors are contiguous in nature, therefore the insertion and deletion operations are costlier as compared to the insertion and deletion option in Lists. list::sort() sort() function is used to sort the
2 min read
is_sorted() in C++ STL In C++, is_sorted() is a built-in function used to check whether the element of the given range is sorted or not in ascending order. In this article, we will learn about is_sorted() function in C++.Letâs take a quick look at a simple example that illustrates is_sorted() method:C++#include <bits/s
4 min read
Internal Working of sort() in C++ In C++, sort() is an STL function used for sorting containers such as arrays, vectors, etc. It provides an efficient and versatile way to sort data in C++. In this article, we will learn how the sort() function internally works.The sort() function uses the algorithm named IntroSort for sorting the g
5 min read
Sort 3 numbers Given three numbers, how to sort them? Examples: Input : arr[] = {3, 2, 1} Output : arr[] = {1, 2, 3} Input : arr[] = {6, 5, 0} Output :arr[] = {0, 5, 6} One simple solution is to use sort function. C++ // C++ program to sort an array of size 3 #include <algorithm> #include <iostream> us
5 min read