RADIX SORT:::::::::
#include <iostream>
#include <vector>
using namespace std;
// Function to get the maximum value in the array
int getMax(const vector<int>& arr) {
int max = arr[0];
for (int i = 1; i < arr.size(); i++) {
if (arr[i] > max) {
max = arr[i];
return max;
// Function to perform counting sort based on a specific digit (exp)
void countingSort(vector<int>& arr, int exp) {
int n = arr.size();
vector<int> output(n);
int count[10] = {0};
// Count occurrences of each digit
for (int i = 0; i < n; i++) {
int index = (arr[i] / exp) % 10;
count[index]++;
// Update count[i] to hold actual positions
for (int i = 1; i < 10; i++) {
count[i] += count[i - 1];
// Build the output array
for (int i = n - 1; i >= 0; i--) {
int index = (arr[i] / exp) % 10;
output[count[index] - 1] = arr[i];
count[index]--;
// Copy output array back to arr
for (int i = 0; i < n; i++) {
arr[i] = output[i];
// Function to perform radix sort
void radixSort(vector<int>& arr) {
int max = getMax(arr);
for (int exp = 1; max / exp > 0; exp *= 10) {
countingSort(arr, exp);
int main() {
int n;
cout << "Enter the number of elements: ";
cin >> n;
vector<int> arr(n);
cout << "Enter " << n << " elements:" << endl;
for (int i = 0; i < n; i++) {
cin >> arr[i];
radixSort(arr);
cout << "Sorted array: ";
for (int i = 0; i < n; i++) {
cout << arr[i] << " ";
cout << endl;
return 0;
Algorithm for Radix Sort (with user input)
1. Start.
2. Take input for the number of elements in the array (n).
3. Create an array of size n and input n elements from the user.
4. Find the maximum number in the array to determine the number of digits.
5. Perform the following steps for each digit place (ones, tens, hundreds, etc.):
o Initialize a stable sorting mechanism (e.g., counting sort) for the current digit place.
o Sort the elements of the array based on the current digit using counting sort.
6. Repeat until all digit places are processed.
7. Print the sorted array.
8. End.
PSEUDOCODE:::::
Function getMax(array, n)
max = array[0]
For i = 1 to n-1
If array[i] > max
max = array[i]
EndIf
EndFor
Return max
EndFunction
Function countingSort(array, n, exp)
Declare output[n], count[10] initialized to 0
For i = 0 to n-1
index = (array[i] / exp) % 10
count[index] = count[index] + 1
EndFor
For i = 1 to 9
count[i] = count[i] + count[i-1]
EndFor
For i = n-1 to 0
index = (array[i] / exp) % 10
output[count[index] - 1] = array[i]
count[index] = count[index] - 1
EndFor
For i = 0 to n-1
array[i] = output[i]
EndFor
EndFunction
Function radixSort(array, n)
max = getMax(array, n)
exp = 1
While max / exp > 0
countingSort(array, n, exp)
exp = exp * 10
EndWhile
EndFunction
Main
Input n
Declare array[n]
For i = 0 to n-1
Input array[i]
EndFor
Call radixSort(array, n)
For i = 0 to n-1
Print array[i]
EndFor
EndMain