by gerggerg · 14y ago · 0 comments
t = array[--m];
Well I don't know if it trips me up so much as it makes me think too much about syntax especially when the focus is on the algorithm itself. When writing educational code I find the following more effective: m -= 1;
t = array[m];
Anyone else have any thoughts?In fact, I was actually thinking more of this example:
i = Math.floor(Math.random() * n--);
when I stumbled across your comment.Otherwise, that's a minor criticism and it's a good page overall. In fact, it was one of the interview questions I was asked when I interviewed at Microsoft a long time ago. At the time, I didn't realize the algorithm actually had a name.
I think that in that particular case the fact the array[m] is used in the next line makes things not as obvious as they could be visually. I feel that the following requires less reading:
m -=1;
t = array[m];
array[m] = array[i];
array[i] = t;
To me, it's faster to parse. 't' equals the value of 'array' at index 'm' minus 1 and 'm' equals itself minus 1.
vs 'm' equals itself minus 1.
't' equals the value of 'array' at index 'm'.
To me one of those seems more concise for writing production code, and the other more useful for teaching algorithms.It sounds confusing that the pieces of such a statement are not executed in the order that they are written, but in reality it's not any more strange than the fact that "a = b;" reads "evaluate b and store in a".
The real problem happens when there are multiple operators like that in the same statement, or multiple appearances of a post/pre-inc/dec-remented variable and you need to parse operator precedence in order to figure out the order of execution. As usual, abusing the syntax leads to confusing code, but simple and straightforward cases like "a = b[--i];" are cleaner and easier to read for anyone competent enough to matter.