Python Program for Stooge Sort

PythonServer Side ProgrammingProgramming

<p style="">In this article, we will learn about the solution to the problem statement given below.</p><p style=""><strong>Problem statement</strong> &minus; We are given an array, we need to sort it using stooge sort.</p><h2>Algorithm</h2><pre class="result notranslate">1. Check if value at index 0 is greater than value at last index,then swap them. 2. sort the initial 2/3rd of the array. 3. sort the last 2/3rd of the array. 4. sort the initial 2/3rd again to confirm.</pre><p>Now let&rsquo;s observe the solution in the implementation below &minus;</p><h2>Example</h2><p><a class="demo" href="" rel="nofollow" target="_blank">&nbsp;Live Demo</a></p><pre class="prettyprint notranslate" style="">def stoogesort(arr, l, h): &nbsp; &nbsp;if l &gt;= h: &nbsp; &nbsp; &nbsp; return &nbsp; &nbsp;# swap &nbsp; &nbsp;if arr[l]&gt;arr[h]: &nbsp; &nbsp; &nbsp; t = arr[l] &nbsp; &nbsp; &nbsp; arr[l] = arr[h] &nbsp; &nbsp; &nbsp; arr[h] = t &nbsp; &nbsp;# more than 2 elements &nbsp; &nbsp;if h-l+1 &gt; 2: &nbsp; &nbsp; &nbsp; t = (int)((h-l+1)/3) &nbsp; &nbsp; &nbsp; # sort first 2/3 elements &nbsp; &nbsp; &nbsp; stoogesort(arr, l, (h-t)) &nbsp; &nbsp; &nbsp; # sort last 2/3 elements &nbsp; &nbsp; &nbsp; stoogesort(arr, l+t, (h)) &nbsp; &nbsp; &nbsp; # sort first 2/3 elements again &nbsp; &nbsp; &nbsp; stoogesort(arr, l, (h-t)) # main arr = [1,4,2,3,6,5,8,7] n = len(arr) stoogesort(arr, 0, n-1) print (&quot;Sorted sequence is:&quot;) for i in range(0, n): &nbsp; &nbsp;print(arr[i], end = &quot; &quot;)</pre><h2>Output</h2><pre class="result notranslate">Sorted sequence is: 1 2 3 4 5 6 7 8</pre><p style=""><img src="" class="fr-fic fr-dib" width="474" height="194"></p><p>All the variables are declared in the local scope and their references are seen in the figure above.</p><h2>Conclusion &minus;</h2><p>In this article, we have learned about how we can make a Python Program for Stooge Sort</p>
Updated on 20-Dec-2019 06:55:01