>include <iostream#
>include <vector#
;using namespace std
Function to get the maximum number in the array //
{ int getMax(const vector<int>& arr)
;int maxVal = arr[0]
for (int num : arr)
if (num > maxVal)
;maxVal = num
;return maxVal
Counting sort for a specific digit place (exp) //
{ void countingSort(vector<int>& arr, int exp)
;)(int n = arr.size
vector<int> output(n); // Output array
int count[10] = {0}; // Count array for digits (0-9)
Count occurrences of each digit at the current place //
for (int i = 0; i < n; i++)
;++count[(arr[i] / exp) % 10]
Update count[i] to store position of the next occurrence //
for (int i = 1; i < 10; i++)
;count[i] += count[i - 1]
Build the output array using count array //
{ for (int i = n - 1; i >= 0; i--)
;output[count[(arr[i] / exp) % 10] - 1] = arr[i]
;--count[(arr[i] / exp) % 10]
Copy the sorted elements back to the original array //
for (int i = 0; i < n; i++)
;arr[i] = output[i]
Radix Sort function //
{ void radixSort(vector<int>& arr)
int maxVal = getMax(arr); // Get the maximum number
Apply counting sort to each digit place (1s, 10s, 100s, ...) //
for (int exp = 1; maxVal / exp > 0; exp *= 10)
;countingSort(arr, exp)
Function to print the array //
{ void printArray(const vector<int>& arr)
for (int num : arr)
;" " << cout << num
;cout << endl
Main function //
{ )(int main
;vector<int> arr = {170, 45, 75, 90, 802, 24, 2, 66}
;" :cout << "Original array
;printArray(arr)
;radixSort(arr)
;" :cout << "Sorted array
;printArray(arr)
;return 0
------¯---
Function to get the maximum number in the array #
:def get_max(arr)
return max(arr)
Counting sort for a specific digit place (exp) #
:def counting_sort(arr, exp)
n = len(arr)
output = [0] * n # Output array
count = [0] * 10 # Count array for digits (0-9)
Count occurrences of each digit at the current place #
:for i in range(n)
index = (arr[i] // exp) % 10
count[index] += 1
Update count[i] to store the position of the next occurrence #
:for i in range(1, 10)
count[i] += count[i - 1]
Build the output array using the count array #
:for i in range(n - 1, -1, -1)
index = (arr[i] // exp) % 10
output[count[index] - 1] = arr[i]
count[index] -= 1
Copy the sorted elements back to the original array #
:for i in range(n)
arr[i] = output[i]
Radix Sort function #
:def radix_sort(arr)
max_val = get_max(arr) # Get the maximum number
Apply counting sort to each digit place (1s, 10s, 100s, ...) #
exp = 1
:while max_val // exp > 0
counting_sort(arr, exp)
exp *= 10
Function to print the array #
:def print_array(arr)
print(" ".join(map(str, arr)))
Main function #
:"__if __name__ == "__main
arr = [170, 45, 75, 90, 802, 24, 2, 66]
print("Original array: ", end="")
print_array(arr)
radix_sort(arr)
print("Sorted array: ", end="")
print_array(arr)