快速排序递归函数中arr.length==0判断语句的作用咨询
if(arr.length == 0){ return []; } Line in Your Quicksort Hey there! Let's break down exactly why that line is essential to your quicksort function, and why removing it causes that frustrating stack overflow error.
What's this line doing?
This is the base case for your recursive quicksort algorithm. Recursive functions need a clear stopping condition to avoid running forever, and this line serves exactly that purpose:
- When an empty array is passed to
qSort(), it immediately returns an empty array instead of continuing with the rest of the function logic, putting an end to that branch of recursion.
Why removing it causes a stack overflow
Let's walk through what happens when you comment out that line, using a small example from your sorting process:
Suppose we end up with a subarray of length 1 (like [20]) during the sort. Here's what unfolds:
pivot = arr[0](which is 20)- The for loop runs from
i=1toarr.length-1(which is 0), so the loop never executes.leftandrightstay empty arrays. - The function tries to return
qSort(left).concat(pivot, qSort(right))— which means callingqSort([])twice. - Since there's no base case for empty arrays, each call to
qSort([])will repeat steps 1-3 indefinitely: it tries to accessarr[0](which isundefined, but that's not the immediate crash cause), then callsqSort([])again forleftandright.
This creates an infinite recursion loop. Every recursive call adds a new entry to the browser's call stack, and eventually, the stack hits its maximum allowed size — hence the Uncaught RangeError: Maximum call stack size exceeded error.
A small improvement you can make
You can actually expand the base case to handle arrays of length 1 as well, since a single element is already sorted:
if(arr.length <= 1){ return arr; }
This avoids unnecessary recursive calls for single-element arrays, making your function a bit more efficient and cleaner.
内容的提问来源于stack exchange,提问作者claudiopb

