Trying to understand radix sort for my data structures class. My teacher showed us a sample of radix sort in C++. I don't understand what the for loop for the digits does, she said something about maximum digits. Also when I try this in VS it says log10 is an ambiguous call to an overloaded function.
void RadixSort(int A[], int size)
{
int d = 1;
for(int i = 0; i < size; ++i)
{
int digits_temp;
digits_temp=(int)log10(abs(A[i]!=0 ? abs(A[i]) : 1)) +1;
if(digits_temp > d)
d = digits_temp;
}
d += 1;
*rest of the implementation*
}
Can anyone explain what this for loop does and why i get that ambiguous call error? Thanks
That piece of code is just a search for the number of digits needed for the "longest" integer; that's probably needed to allocate some buffer later.
log10
gives you the power of ten that corresponds to its argument, which, rounded to the next integer (hence the +1
followed by the (int)
cast, which results in truncation), gives you the number of digits required for the number.
The argument of log10
is a bit of a mess, since abs
is called twice when just once would suffice. Still, the idea is to pass to log10
the absolute value of the number being examined if it's not zero, or 1 if it is zero - this because, if the argument were zero, the logarithm would diverge to minus infinity (which is not desirable in this case, I think that the conversion to int
would lead to strange results).
The rest of the loop is just the search for the maximum: at each iteration it calculates the digits needed for the current int being examined, checks if it's bigger than the "current maximum" (d
) and, if it is, it replaces the "current maximum".
The d+=1
may be for cautionary purposes (?) or for the null-terminator of the string being allocated, it depends on how d
is used afterward.
As for the "ambiguous call" error: you get it because you are calling log10
with an int
argument, which can be converted equally to float
, double
and long double
(all types for which log10
is overloaded), so the overload to choose is not clear to the compiler. Just stick a (double)
cast before the whole log10
argument.
By the way, that code could have been simplified/optimized by just looking for the maximum int
(in absolute value) and then taking the base-10 logarithm to discover the number of digits needed.