5

I'm wondering how it works. I guess that "right[r++]" increments "r" in while loop. Or it shows which element of "right" we push to "result"?

function merge(left, right){
  var result = [],
      lLen = left.length,
      rLen = right.length,
      l = 0,
      r = 0;
  while(l < lLen && r < rLen){
     if(left[l] < right[r]){
       result.push(left[l++]);
     }
     else{
       result.push(right[r++]);
    }
  }  
  return result.concat(left.slice(l)).concat(right.slice(r));
}

Thank you.

1
  • the question is, what does not work, what is your problem?
    – webdeb
    Jan 14, 2016 at 19:02

2 Answers 2

6
result.push(right[r++]);

is essentially shorthand for

result.push(right[r]);
r = r + 1;

The ++ operator after the variable returns the variable's value before it gets incremented.

For comparison, using it before the variable

result.push(right[++r]);

would achieve the same result as

r = r + 1;
result.push(right[r]);
1
  • 2
    ++r will increment before return ;)
    – webdeb
    Jan 14, 2016 at 19:00
1

right[r++] is same like writing this:

right[r]
r=r+1

This was called post-increment. There is also pre-increment. It would be written like this:

right[++r]

It would be eqvivalent to

r=r+1
right[r]

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.