This commit is contained in:
krahets
2024-05-01 07:30:15 +08:00
parent 85f0bc4ed1
commit d246e08cc6
68 changed files with 220 additions and 220 deletions
+2 -2
View File
@@ -3574,7 +3574,7 @@
<!-- Page content -->
<h1 id="112-selection-sort">11.2 &nbsp; Selection sort<a class="headerlink" href="#112-selection-sort" title="Permanent link">&para;</a></h1>
<p><u>Selection sort</u> works on a very simple principle: it starts a loop where each iteration selects the smallest element from the unsorted interval and moves it to the end of the sorted interval.</p>
<p>Suppose the length of the array is <span class="arithmatex">\(n\)</span>, the algorithm flow of selection sort is as shown below.</p>
<p>Suppose the length of the array is <span class="arithmatex">\(n\)</span>, the algorithm flow of selection sort is as shown in Figure 11-2.</p>
<ol>
<li>Initially, all elements are unsorted, i.e., the unsorted (index) interval is <span class="arithmatex">\([0, n-1]\)</span>.</li>
<li>Select the smallest element in the interval <span class="arithmatex">\([0, n-1]\)</span> and swap it with the element at index <span class="arithmatex">\(0\)</span>. After this, the first element of the array is sorted.</li>
@@ -3871,7 +3871,7 @@
<ul>
<li><strong>Time complexity of <span class="arithmatex">\(O(n^2)\)</span>, non-adaptive sort</strong>: There are <span class="arithmatex">\(n - 1\)</span> rounds in the outer loop, with the unsorted interval length starting at <span class="arithmatex">\(n\)</span> in the first round and decreasing to <span class="arithmatex">\(2\)</span> in the last round, i.e., the outer loops contain <span class="arithmatex">\(n\)</span>, <span class="arithmatex">\(n - 1\)</span>, <span class="arithmatex">\(\dots\)</span>, <span class="arithmatex">\(3\)</span>, <span class="arithmatex">\(2\)</span> inner loops respectively, summing up to <span class="arithmatex">\(\frac{(n - 1)(n + 2)}{2}\)</span>.</li>
<li><strong>Space complexity of <span class="arithmatex">\(O(1)\)</span>, in-place sort</strong>: Uses constant extra space with pointers <span class="arithmatex">\(i\)</span> and <span class="arithmatex">\(j\)</span>.</li>
<li><strong>Non-stable sort</strong>: As shown in the Figure 11-3 , an element <code>nums[i]</code> may be swapped to the right of an equal element, causing their relative order to change.</li>
<li><strong>Non-stable sort</strong>: As shown in Figure 11-3, an element <code>nums[i]</code> may be swapped to the right of an equal element, causing their relative order to change.</li>
</ul>
<p><a class="glightbox" href="../selection_sort.assets/selection_sort_instability.png" data-type="image" data-width="100%" data-height="auto" data-desc-position="bottom"><img alt="Selection sort instability example" class="animation-figure" src="../selection_sort.assets/selection_sort_instability.png" /></a></p>
<p align="center"> Figure 11-3 &nbsp; Selection sort instability example </p>