CodexBloom - Programming Q&A Platform

Handling Dynamic Input Size in a Radix Sort Implementation in C++

👀 Views: 98 💬 Answers: 1 📅 Created: 2025-06-03
sorting radix-sort vector C++

I'm reviewing some code and I'm having trouble with I'm trying to debug I tried several approaches but none seem to work. I'm getting frustrated with I've searched everywhere and can't find a clear answer. I'm currently trying to implement a Radix Sort algorithm in C++ to handle sorting of large datasets, but I'm working with scenarios with dynamic input sizes. My current implementation assumes a fixed size for the input array, which is not ideal for my use case. I want to allow variable input sizes while ensuring the algorithm remains efficient. Here's the code I've written so far: ```cpp #include <iostream> #include <vector> #include <algorithm> void countingSort(std::vector<int>& arr, int exp) { int n = arr.size(); std::vector<int> output(n); int count[10] = {0}; for (int i = 0; i < n; i++) count[(arr[i] / exp) % 10]++; for (int i = 1; i < 10; i++) count[i] += count[i - 1]; for (int i = n - 1; i >= 0; i--) { output[count[(arr[i] / exp) % 10] - 1] = arr[i]; count[(arr[i] / exp) % 10]--; } for (int i = 0; i < n; i++) arr[i] = output[i]; } void radixSort(std::vector<int>& arr) { int maxVal = *max_element(arr.begin(), arr.end()); for (int exp = 1; maxVal / exp > 0; exp *= 10) countingSort(arr, exp); } int main() { std::vector<int> arr = {170, 45, 75, 90, 802, 24, 2, 66}; radixSort(arr); for (int num : arr) std::cout << num << " "; return 0; } ``` The question arises when I try to sort a vector that I've filled dynamically based on user input. For instance, if the user inputs 10 numbers, it works fine, but if they input fewer than that or a different count, I receive an out-of-bounds behavior or incorrect sorting results. I've tried modifying the `countingSort` function to handle different sizes by dynamically allocating the `output` vector, but it didn’t resolve the issues. I suspect it might be related to how I'm calculating `maxVal`. Can anyone suggest a way to adapt this implementation for dynamic input sizes, or point out any potential pitfalls in my current approach? I'm compiling this on GCC 9.3.0 and using C++11. Any insights or suggestions would be greatly appreciated! I'm working on a application that needs to handle this. What am I doing wrong? The stack includes C++ and several other technologies. What would be the recommended way to handle this? The project is a desktop app built with C++. I'm using C++ 3.11 in this project.