Reputation: 5462
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];
Upvotes: 2
Views: 121
Reputation: 2297
This aux[count[a[i]]++] = a[i];
means:
first, take a[i]
value, and use it as index for count. Then that value use as index in aux
array and place the value of a[i]
to its place. Then increment the value on position count[a[i]]
for 1
.
Its like this:
aux[count[a[i]]] = a[i];
count[a[i]] = count[a[i]] + 1;
but shorter.
You have also this:
aux[++count[a[i]]] = a[i];
.
This will take value from count[a[i]]
and first increment for 1
and then use it as index in aux
array, so now we search it as:
count[a[i]] = count[a[i]] + 1;
aux[count[a[i]]] = a[i];
As you can see, aux[count[a[i]]+1]
is not like aux[count[a[i]]++]
, since it will not store increased value of a[i]
for 1 in a[i]
, and it will take index a[i] + 1
from aux
, but aux[count[a[i]]++]
takes index of a[i]
.
aux[count[a[i]]+1]
is similar to aux[++count[a[i]]]
but the difference is you didn't increment the value in count[a[i]]
.
Upvotes: 2
Reputation: 1499760
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.
Upvotes: 3