#include <iostream> #include <cmath> #include <vector> using namespace std; // Function to perform Counting Sort based on digit place (1s, 10s, 100s, etc.) void countSort(int arr[], int n, int exponent) { std::vector<int> count(n,0); for(int i=0;i<n;i++){ count[(arr[i]/exponent)%10]++; } for(int i=1;i<n;i++){ count[i] = count[i] + count[i-1]; } std::vector<int> ans(n,0); for(int i=n-1;i>=0;i--){ int index = --count[(arr[i]/exponent)%10]; ans[index] = arr[i]; } for(int i=0;i<n;i++){ arr[i] = ans[i]; } } // Function to perform Radix Sort on the array. void radixSort(int arr[], int n) { int maxNumber = arr[0]; for(int i=1;i<n;i++){ if(maxNumber<arr[i]){ maxNumber= arr[i]; } } maxNumber = int(log10(maxNumber) + 1); int exponent = 1; for(int i=0;i<maxNumber;i++){ countSort(arr,n,exponent); exponent = exponent*10; } } // Function to initiate the Radix Sort process. void processRadixSort(int arr[], int n) { if(n>1){ radixSort(arr,n); } } void displayArray(int arr[], int n) { for (int i = 0; i < n; i++) { cout << arr[i] << " "; } cout << endl; } // Function to dynamically allocate an array and fill it with random values. void fillDynamicArrayWithRandomValues(int** arr, int* n) { cout << "Enter the size of the array: "; cin >> *n; *arr = new int[*n]; srand(time(0)); // Seed for random number generation for (int i = 0; i < *n; i++) { (*arr)[i] = rand() % 1000; // Fill with random numbers between 0 and 999 } } int main() { int* arr; int n; fillDynamicArrayWithRandomValues(&arr, &n); cout << "Unsorted array: "; displayArray(arr, n); processRadixSort(arr, n); cout << "Sorted array: "; displayArray(arr, n); delete[] arr; // Deallocate dynamically allocated memory return 0; }
Preview:
downloadDownload PNG
downloadDownload JPEG
downloadDownload SVG
Tip: You can change the style, width & colours of the snippet with the inspect tool before clicking Download!
Click to optimize width for Twitter