简体   繁体   中英

javascript - Issue in the loop in algorithm exercise

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

If the given array has a length of 0 (is empty), just return an empty array, because there is no sorting to be done. Actually the line could be:

if(arr.length <= 1){
  return arr;
}

since for 0 and 1 elements the's no sorting to be done.

This is related to the function being recursive (it calls itself) and therefor it needs a case, at wich it stops calling itself and return a value. That's called a recursion anchor.

This is called the base case of recursion , which ends the recursion. If you leave it away, qSort will call qSort will call qSort will call...

This line was written for optimization.

If there is no data in array you have nothing to sort. Plus when you sort elements you are passing smaller and smaller chunks of base array to qSort function, so you have to finish qSort execution at one point.

So basically it tells the code "There is nothing to sort".

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM