I was reading radix sort
from this site I am confused in the 3rd for loop
:
for (i = n - 1; i >= 0; i--) {
output[freq[(arr[i] / place) % range] - 1] = arr[i];
freq[(arr[i] / place) % range]--;
}
Why did they start it from the end as when I tried to start it from 0, it gives me the wrong answer? Any explanation or solution would be appreciated.
Because
freq
contains the cumulative number of elements in each position in the range. That is, for a range of i=0-9,freq[i]
contains the number of digits that are placed on positions0, ..., i
.The algorithm uses
freq
to keep track of how many items it needs to draw from initial array to the output array for each position.Assuming 10,21,17,34,44,11,654,123 as input, running count-sort for first insignificant digit:
freq
would be as:So, the array becomes 10,21,11,123,34,44,654,17.
You need to loop backwards to keep the original order of numbers with the same digit, because how the
freq
is built. Suppose you want to place 34 to its right place on the output. According to thefreq
array, if loop forward, you would place it on the 7th position which is incorrect. If you loop backwards, you have already placed 654 and 44 before reaching 34, sofreq[4]=5
by then which is the correct place.