I am trying to work out how this function operates,
function mergeSort(a) {
if (a.length === 1) return a;
const mid = Math.trunc(a.length / 2);
const left = mergeSort(a.slice(0, mid));
const right = mergeSort(a.slice(mid));
const result = [];
((l, r) => {
let i = 0,
j = 0;
while (i < l.length && j < r.length) {
l[i] < r[j] ? result.push(l[i ]) : result.push(r[j ]);
}
while (i < l.length) result.push(l[i ]);
while (j < r.length) result.push(r[j ]);
})(left, right);
return result;
}
const random = [10, 5, 2, 7, 3, 4];
I dont understand what is keeping the left side / right side in its memory.
on the first iteration the Immediately Invoked Function Expression (IIFE) has the parameters [5,2] because [1] was returned. It then sorts [5,2]. why then does the IIFE run again sorting left[10], right[2,5]? what causes this action?
CodePudding user response:
I dont understand what is keeping the left side / right side in its memory
The left/right side is kept in the left
and right
variables for each function call. Since variables are function-scoped that means that each call can have their own version of left
and right
Merge sort is a classic example of the "Divide and conquer" method. The input array is split into smaller and smaller fractions through recursion. The recursion happens until we're left with 1 element units.
After that it's just a matter of merging 2 sorted arrays on the way up out of the recursion.
There are very neat websites showcasing the visualization of algorithms. Take a look at this website here
Edit: As Dai mentioned in his comment. Try to run this code through a debugger. It'll give you a better overview on how exactly your code runs line by line.