hopefully the code is clear (with the output). It seems to show recursion:
- evaluating all in one go (asynchronously?)
- executing statements from before the call 1st and in sync
- then executing statements from after the call and in reverse sync, giving a mirror effect.
i may be misunderstanding synchronicity, but i don’t know why it appears (in terms of output) to go into reverse
(sorry, this post explains better when you copy the code to editor to see output)
const recurse = array => {
if(array.length <= 1) { return array }
const midIndex = Math.floor(array.length / 2)
const leftArr = array.slice(0, midIndex)
const rightArr = array.slice(midIndex)
n++
console.log( 'BEFORE', 'left:',leftArr, 'right:',rightArr, 'n:', n, 'p:', p)
recurse(leftArr)
p++
console.log(' AFTER', 'left:',leftArr, 'right:',rightArr, 'n:', n, 'p:', p)
return leftArr.concat(rightArr)
}
let n = 0, p = 0 // LABELS ONLY n = prevCount ; p = postCount (wrt recursive call)
const array = [1,2,3,4,5,6,7,8,9,10]
console.log('original:', array, '\n','--------')
console.log('--------','\n', 'recursed:', recurse(array))
**Your browser information:**
User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/102.0.5005.115 Safari/537.36
Challenge: Implement Merge Sort
Link to the challenge: