I'm studing an algorithm problem and I did understand all the things except the lines that I marked up with comment into the code. Note: It is not to solve the code. The code is working good. It is only to explain me about what is the marked lines' purposes.
let arr= [40, 50, 80, 20, 21, 35]
function qSort(arr) {
if(arr.length == 0){ // <-- These lines. I did NOT understand its purpose
return [];
}
var left = []
var right = []
var pivot = arr[0]
for(var i= 1; i<arr.length; i++) {
if(arr[i] < pivot) {
left.push(arr[i])
} else {
right.push(arr[i])
}
}
return qSort(left).concat(pivot, qSort(right))
}
console.log(qSort(arr))
This code is working good, but When I comment these lines into the code, the script doesn't work and it cause an error message referencing a loop issue: Uncaught RangeError: Maximum call stack size exceeded
Does anybody explain it to me please? I would like to know what is this lines' purpose. Thanks