c++ - Radix Sorting algorithm difficulties -
i'm having problem understanding how pass user-input value parameter radix sorting algorithm.
my assignment class diagram shown here. can see, class constructor radixsort required take (int radix) , (int exponent). "radix" variable serves numerical base (i.e. base 10) , "exponent" used sort input numbers.
my code works perfectly, except 1 problem: works when input radix directly. here important parts of code:
radixsort(int radix, int exponent): sortroutine() { cout << "radix: " << radix << endl; cout << "exponent: " << exponent << endl; setradix(radix); setexponent(exponent); } void sort(int array[], int size) { cout << "-initiating radix sort-" << endl; setsize(size); int max = getmax(array, size); int radix = getradix(); int * output = new int[size]; (int exponent = getexponent(); max / exponent > 0; exponent *= radix) { radixalgorithm(array, size, radix, exponent, output); } } void radixalgorithm(int array[], int size, int radix, int exponent, int output[]) { int i; int count[10] = { 0 }; (i = 0; < size; i++) count[(array[i] / exponent) % radix]++; (i = 1; < radix; i++) { count[i] += count[i - 1]; } (i = size - 1; >= 0; i--) { output[count[(array[i] / exponent) % radix] - 1] = array[i]; count[(array[i] / exponent) % radix]--; } (i = 0; < size; i++) array[i] = output[i]; (i = 0; < size; i++) { cout << array[i] << " "; } cout << endl; }
from can tell, things go wrong starting in radixalgorithm section:
int count[10] = { 0 };
i'm supposed able take radix user input. however, if try that, making this:
int count[radix] = { 0 };
i error:
array type 'int[radix]' not assignable.
expression did not evaluate constant.
because radix supposed user input, , therefore not constant, dont understand how use radix base of count[ ] array.
is there better way this? did make complicated? dont understand how i'm supposed perform radix sort in other way given i'm forced use form
radixsort( int radix, int exponent);
for constructor.
any advice or improved methods?
you're using
int * output = new int[size];
to allocate array of size known @ runtime. if understand that, can use same approach allocate int * count
work same way. need initialize 0 yourself, , delete []
resulting array when finished.
you instead use std::vector
patrick roberts suggested in comment, more appropriate way in c++, , has benefit of deallocating when goes out of scope:
std::vector<int> count(radix, 0);
int count[radix]
variable length array, present in newer versions of c not c++ (see why aren't variable-length arrays part of c++ standard?).