<?xml version="1.0" encoding="utf-8" standalone="yes"?><rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom"><channel><title>算法 on Wimi's Space</title><link>https://wimi.space/tags/%E7%AE%97%E6%B3%95/</link><description>Recent content in 算法 on Wimi's Space</description><generator>Hugo</generator><language>zh-cn</language><lastBuildDate>Mon, 22 Mar 2021 09:37:53 +0800</lastBuildDate><atom:link href="https://wimi.space/tags/%E7%AE%97%E6%B3%95/index.xml" rel="self" type="application/rss+xml"/><item><title>快速排序算法</title><link>https://wimi.space/posts/2021/03/algorithm-quick-sort/</link><pubDate>Mon, 22 Mar 2021 09:37:53 +0800</pubDate><guid>https://wimi.space/posts/2021/03/algorithm-quick-sort/</guid><description>&lt;blockquote>
&lt;p>快速排序是一种常用的内部排序算法，平均时间复杂度为 O(nlogn)。&lt;/p>&lt;/blockquote>
&lt;h2 id="算法思路">算法思路&lt;/h2>
&lt;p>快速排序使用&lt;strong>分治法来把一个序列分为较小和较大的两个子序列，然后递归地排序两个子序列&lt;/strong>。步骤如下：&lt;/p>
&lt;ol>
&lt;li>&lt;strong>挑选基准值&lt;/strong>: 从序列中选择任意一个元素作为基准，通常选择序列的第一个元素。&lt;/li>
&lt;li>&lt;strong>分割序列&lt;/strong>: 将序列中比基准元素小的元素放到基准前面，大的放在基准后面。&lt;/li>
&lt;li>&lt;strong>递归排序&lt;/strong>: 对较小的和较大的子序列分别进行上述操作。&lt;/li>
&lt;/ol>
&lt;h2 id="举例说明">举例说明&lt;/h2>
&lt;p>例如对序列 [ 3, 5, 4, 1, 2, 6 ] 进行快速排序&lt;/p>
&lt;ol>
&lt;li>
&lt;p>选取元素 3 作为基准元素。
&lt;img src="https://static.wimi.space/blog/quick-sort-01.png" alt="">&lt;/p>
&lt;/li>
&lt;li>
&lt;p>将比 3 小的元素放在 3 前面，大的放在 3 后面，将其分割成两个子序列。
&lt;img src="https://static.wimi.space/blog/quick-sort-02.png" alt="">&lt;/p>
&lt;/li>
&lt;li>
&lt;p>重复上述两个步骤，直到子序列划分完毕。
&lt;img src="https://static.wimi.space/blog/quick-sort-03.png" alt="">&lt;/p>
&lt;/li>
&lt;/ol>
&lt;h2 id="划分序列">划分序列&lt;/h2>
&lt;p>序列划分有两种常用的方式。&lt;/p>
&lt;h3 id="方法一">方法一&lt;/h3>
&lt;blockquote>
&lt;p>从左到右遍历并调整交换位置，用 offset 记录偏移的量，用于填充基准元素。&lt;/p>&lt;/blockquote>
&lt;ol>
&lt;li>
&lt;p>初始化 offset 基准元素后的第一个位置 ( 即 offset = low + 1 )，从 offset 位置开始往后扫描，找到比 3 小的元素 1，交换 1 和基准外第一个位置的元素 5，交换后 offset 自增。
&lt;img src="https://static.wimi.space/blog/quick-sort-04.png" alt="">&lt;/p>
&lt;/li>
&lt;li>
&lt;p>找到比 3 小的元素 2，交换 2 和基准外第二个位置的元素 4，交换后 offset 自增。
&lt;img src="https://static.wimi.space/blog/quick-sort-05.png" alt="">&lt;/p></description></item></channel></rss>