I came across a rather peculiar shorthand notation: A[j+1] = A[j--]
It seems that this line does two operations: move A[j] right and decrement j
is it possible to break this down into individual steps to help me understand the shorthand?
Pseudo code:
n=A.length
for i <- 1 to n-1
curr = A[i]
j = i - 1
while j >= 0 && A[j] > curr
A[j+1] = A[j--]
A[j+1] = curr
Sure:
Note that the
targetIndexis computed before anything else happens – the left hand side of the assignment operator is effectively determined before the right hand side.However, the decrement happens before the assignment itself takes place, and even before the right hand array access is evaluated. You can see that in this sample code:
Here, you can see that
jhas been decremented even though the assignment itself can’t take place.Indeed, the same happens if we use
x[j + 10] = x[j--];– in other words, if it’s the target index which is out of bounds. By the time that’s discovered, the decrement has already occurred.