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.
Definition and Usage. The while statement creates a loop (araund a code block) that is executed while a condition is true . The loop runs while the condition is true . Otherwise it stops.
Using while to iterate over an array We can even use while loops to iterate over an array. First we define an array and find out its length, len , using the length property of arrays. Then we define an index variable to iterate over the array .
Syntax. The while loop starts by evaluating condition . If condition evaluates to true , the code in the code block gets executed. If condition evaluates to false , the code in the code block is not executed and the loop ends.
In most computer programming languages, a do while loop is a control flow statement that executes a block of code at least once, and then either repeatedly executes the block, or stops executing it, depending on a given boolean condition at the end of the block.
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]);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With