gh-pages
krahets 12 months ago
parent d8210b38d3
commit 78e91e9e2e

@ -4377,7 +4377,7 @@
</div>
</div>
<h2 id="1155">11.5.5 &nbsp; 尾递归优化<a class="headerlink" href="#1155" title="Permanent link">&para;</a></h2>
<p><strong>在某些输入下,快速排序可能占用空间较多</strong>。以完全序的输入数组为例,设递归中的子数组长度为 <span class="arithmatex">\(m\)</span> ,每轮哨兵划分操作都将产生长度为 <span class="arithmatex">\(0\)</span> 的左子数组和长度为 <span class="arithmatex">\(m - 1\)</span> 的右子数组,这意味着每一层递归调用减少的问题规模非常小(只减少一个元素),递归树的高度会达到 <span class="arithmatex">\(n - 1\)</span> ,此时需要占用 <span class="arithmatex">\(O(n)\)</span> 大小的栈帧空间。</p>
<p><strong>在某些输入下,快速排序可能占用空间较多</strong>。以完全序的输入数组为例,设递归中的子数组长度为 <span class="arithmatex">\(m\)</span> ,每轮哨兵划分操作都将产生长度为 <span class="arithmatex">\(0\)</span> 的左子数组和长度为 <span class="arithmatex">\(m - 1\)</span> 的右子数组,这意味着每一层递归调用减少的问题规模非常小(只减少一个元素),递归树的高度会达到 <span class="arithmatex">\(n - 1\)</span> ,此时需要占用 <span class="arithmatex">\(O(n)\)</span> 大小的栈帧空间。</p>
<p>为了防止栈帧空间的累积,我们可以在每轮哨兵排序完成后,比较两个子数组的长度,<strong>仅对较短的子数组进行递归</strong>。由于较短子数组的长度不会超过 <span class="arithmatex">\(n / 2\)</span> ,因此这种方法能确保递归深度不超过 <span class="arithmatex">\(\log n\)</span> ,从而将最差空间复杂度优化至 <span class="arithmatex">\(O(\log n)\)</span> 。代码如下所示:</p>
<div class="tabbed-set tabbed-alternate" data-tabs="5:12"><input checked="checked" id="__tabbed_5_1" name="__tabbed_5" type="radio" /><input id="__tabbed_5_2" name="__tabbed_5" type="radio" /><input id="__tabbed_5_3" name="__tabbed_5" type="radio" /><input id="__tabbed_5_4" name="__tabbed_5" type="radio" /><input id="__tabbed_5_5" name="__tabbed_5" type="radio" /><input id="__tabbed_5_6" name="__tabbed_5" type="radio" /><input id="__tabbed_5_7" name="__tabbed_5" type="radio" /><input id="__tabbed_5_8" name="__tabbed_5" type="radio" /><input id="__tabbed_5_9" name="__tabbed_5" type="radio" /><input id="__tabbed_5_10" name="__tabbed_5" type="radio" /><input id="__tabbed_5_11" name="__tabbed_5" type="radio" /><input id="__tabbed_5_12" name="__tabbed_5" type="radio" /><div class="tabbed-labels"><label for="__tabbed_5_1">Python</label><label for="__tabbed_5_2">C++</label><label for="__tabbed_5_3">Java</label><label for="__tabbed_5_4">C#</label><label for="__tabbed_5_5">Go</label><label for="__tabbed_5_6">Swift</label><label for="__tabbed_5_7">JS</label><label for="__tabbed_5_8">TS</label><label for="__tabbed_5_9">Dart</label><label for="__tabbed_5_10">Rust</label><label for="__tabbed_5_11">C</label><label for="__tabbed_5_12">Zig</label></div>
<div class="tabbed-content">

File diff suppressed because one or more lines are too long

Binary file not shown.
Loading…
Cancel
Save