You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

快速排序递归函数中arr.length==0判断语句的作用咨询

Understanding the 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:

  1. pivot = arr[0] (which is 20)
  2. The for loop runs from i=1 to arr.length-1 (which is 0), so the loop never executes. left and right stay empty arrays.
  3. The function tries to return qSort(left).concat(pivot, qSort(right)) — which means calling qSort([]) twice.
  4. Since there's no base case for empty arrays, each call to qSort([]) will repeat steps 1-3 indefinitely: it tries to access arr[0] (which is undefined, but that's not the immediate crash cause), then calls qSort([]) again for left and right.

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.28 06:57:59