So there's a piece of an radix sort implemented Java code that reads as below:
aux[count[a[i]]++] = a[i];
Why use a post increment operator? Why not aux[count[a[i]]+1]? Is the post increment simply to increment the value in count[a[i]] by 1 and store it there?
radixSort.java
int N = a.length;
int[] count = new int[R+1];
for (int i = 0; i < N; i++)
count[a[i]+1]++;
for (int r = 0; r < R; r++)
count[r+1] += count[r];
for (int i = 0; i < N; i++)
aux[count[a[i]]++] = a[i];
for (int i = 0; i < N; i++)
a[i] = aux[i];
Is the post increment simply to increment the value in count[a[i]] by 1 and store it there?
Yes, exactly. There are two side-effects of the statement: one is a modification to an element of aux
, and the other is a modification to an element in count
.
Personally I'd avoid writing it like that - I'd probably write:
// We don't use i other than to index into a, so use an
// enhanced for loop instead
for (int value : a)
{
aux[count[value]] = value;
count[value]++;
}
Note that even if the change to count
weren't required, aux[count[a[i]]+1]
wouldn't do the same thing - because aux[count[a[i]]++]
refers to the element in aux
with index count[a[i]]
, before the increment, because ++
is being used as a post-increment here.
See more on this question at Stackoverflow