<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by anonymous on Medium]]></title>
        <description><![CDATA[Stories by anonymous on Medium]]></description>
        <link>https://medium.com/@ssxenoz1?source=rss-5b7a6f6f0ff3------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/proxy/1*TGH72Nnw24QL3iV9IOm4VA.png</url>
            <title>Stories by anonymous on Medium</title>
            <link>https://medium.com/@ssxenoz1?source=rss-5b7a6f6f0ff3------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 04:11:12 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@ssxenoz1/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Push_swap: We Tried to Sort Numbers. Here’s What Happened.]]></title>
            <link>https://medium.com/@ssxenoz1/push-swap-we-tried-to-sort-numbers-heres-what-happened-f5d337327a0b?source=rss-5b7a6f6f0ff3------2</link>
            <guid isPermaLink="false">https://medium.com/p/f5d337327a0b</guid>
            <dc:creator><![CDATA[anonymous]]></dc:creator>
            <pubDate>Wed, 25 Nov 2026 14:43:29 GMT</pubDate>
            <atom:updated>2026-11-25T14:43:29.068Z</atom:updated>
            <content:encoded><![CDATA[<p><em>How my friend and I approached Push_swap, why we picked each algorithm, and what we still don’t know.</em></p><h3>How it started</h3><p>When my friend and I started Push_swap, we thought it would be a normal sorting project. We both knew how to sort an array, so we assumed this was the same thing with a different wrapper.</p><p>Then we read the subject properly.</p><p>There are two stacks, A and B. All the numbers start in A, B is empty, and we only get a small set of instructions: swap, push, rotate, and reverse rotate. At the end, A must be sorted and B must be empty.</p><p>The part that changed how we saw the project was the score. Nobody asks whether the program sorts correctly — that’s the minimum. What matters is <strong>how many instructions it prints</strong>. For 100 numbers, the limit is 700, and for 500 numbers, it’s 5,500.</p><p>So the real question stopped being “How do we sort?” and became “How do we sort while paying as little as possible for every move?”</p><h3>What makes it hard</h3><p>You can only touch the <strong>top</strong> of a stack. Reaching anything deeper costs rotations, and every rotation is an instruction that counts against you.</p><p>Our instructions are:</p><ul><li>sa, sb: swap the top two elements of a stack.</li><li>pa, pb: push the top element from one stack to the other.</li><li>ra, rb: rotate a stack; the top goes to the bottom.</li><li>rra, rrb: reverse rotate a stack; the bottom goes to the top.</li></ul><p>Everything we did in this project is about one thing:</p><p><strong>How far is the number I want from the top?</strong></p><h3>Our plan</h3><p>We didn’t want to pick one algorithm and hope it worked. We decided to build three algorithms of increasing difficulty, so we could compare how each one behaves:</p><ul><li><strong>Simple:</strong> Selection Sort.</li><li><strong>Medium:</strong> Rank-based Chunk Sort.</li><li><strong>Complex:</strong> Radix Sort.</li></ul><p>Then, once we understood how they behaved, we added a fourth idea on top of them. That comes later.</p><h3>The simple algorithm: Selection Sort</h3><h3>How it works</h3><p>The idea is the classic one: find the smallest element, put it aside, and repeat. On two stacks, “put it aside” means pushing it to B.</p><p>Each round, we look for the smallest number in A and calculate how many rotations it takes to bring it to the top. Then we choose the shortest direction: ra if the number is in the top half of A, or rra if it&#39;s in the bottom half.</p><p>After rotating, we push it to B. We repeat this until only three numbers are left in A, sort those three directly, and push everything back.</p><p>Since we always push the smallest first, the biggest number ends up on top of B. When we push everything back to A, the order flips, and A comes out sorted with the smallest on top.</p><pre>selection_sort(A, B):<br>    while size(A) &gt; 3:<br>        min = smallest element in A<br>        rotations = number of moves needed to bring min to the top</pre><pre>        if min is in the top half of A:<br>            do &#39;ra&#39; rotations times<br>        else:<br>            do &#39;rra&#39; rotations times</pre><pre>        pb                  // push min to B</pre><pre>    sort_3(A)               // hardcoded sort for the last 3</pre><pre>    while B is not empty:<br>        pa                  // push back to A</pre><p><em>This animation is the classic array version, not the two-stack version, but the idea is the same: find the minimum, move it out, and repeat.</em></p><h3>Why we chose it</h3><p>We selected Selection Sort because its logic maps naturally to stack operations. At each iteration, we locate the minimum element, calculate its position, and determine the shortest rotation path to bring it to the top.</p><p>It also provided a simple way to validate our rotation logic, position calculations, and push operations before moving to more complex algorithms.</p><h3>The medium algorithm: Rank-based Chunk Sort</h3><h3>How it works</h3><p>Selection Sort has a weakness. Every round, it goes looking for the minimum wherever it is. If the input is shuffled, the minimum is usually far from the top, and we pay a lot of rotations every single time.</p><p>For the second algorithm, we wanted more control over where the numbers go.</p><p>First, we give every number a <strong>rank</strong>: its position in the sorted order, from 0 to n — 1. Ranks let us talk about “the 10 smallest numbers” without comparing actual values.</p><p>Then we split the ranks into chunks. The number of chunks is about the square root of n, and the chunk size is n divided by the number of chunks, rounded up. For 100 numbers, that’s 10 chunks of 10.</p><p>We go through A. If the top element’s rank is inside the current chunk, we push it to B. If not, we rotate A and look at the next one. When a chunk is complete, we move to the next.</p><p>At that point, B is organized by chunk: the small chunks are deep, while the big ones are on top.</p><p>We bring everything back by finding the biggest number in B, rotating B the shortest way to bring it to the top, and pushing it to A. Because of the chunk structure, the biggest number is never very far from the top or the bottom, so these rotations stay small.</p><pre>chunk_sort(A, B):<br>    give every number in A its rank (0 to n - 1)</pre><pre>    chunks = floor(sqrt(n))<br>    chunk_size = ceil(n / chunks)</pre><pre>    limit = chunk_size<br>    pushed = 0</pre><pre>    while size(A):<br>        if rank(top of A) &lt; limit:<br>            pb<br>            pushed = pushed + 1</pre><pre>            if pushed == limit:<br>                limit = limit + chunk_size<br>        else:<br>            ra</pre><pre>    while B is not empty:<br>        max = biggest element in B<br>        bring max to the top of B using the shortest rotation (rb or rrb)<br>        pa</pre><p><em>The image below shows a universal chunk sort working with an array. One thing our strategy does differently is that we don’t sort the elements inside those chunks. Instead, we look for the greatest number and push it back. The general idea is still the same.</em></p><h3>Why we chose it</h3><p>We chose it because it keeps the idea of Selection Sort — always bring the biggest or smallest element to the top — but removes its biggest problem.</p><p>Selection Sort’s cost grows with how far the minimum is, and in a shuffled input that distance can be huge. Chunks let us push numbers to B in a rough order, so that later the next number we need is already close.</p><h3>The complex algorithm: Radix Sort</h3><h3>How it works</h3><p>For the third algorithm, we wanted something that doesn’t compare numbers with each other at all. Since we already had ranks, Radix Sort was a natural choice. It reads the ranks in binary, one bit at a time.</p><p>For each bit, starting from the lowest one, we go through all of A. If the bit of the top number is 0, we push it to B. If it’s 1, we rotate A to leave it there.</p><p>When we’ve been through everything, we push all of B back to A. After the last bit, A is sorted.</p><p>The number of passes depends on the biggest rank. For 100 numbers, the biggest rank is 99, which needs 7 bits, so there are 7 passes. For 500 numbers, it’s 9 passes.</p><pre>radix_sort(A, B):<br>    give every number in A its rank (0 to n - 1)</pre><pre>    max_bits = number of bits needed to write (n - 1)</pre><pre>    for bit from 0 to max_bits - 1:<br>        repeat n times:<br>            if bit number &#39;bit&#39; of rank(top of A) is 0:<br>                pb<br>            else:<br>                ra</pre><pre>        while B is not empty:<br>            pa</pre><p><em>This image uses base 10, working with integers, but the general idea stays the same.</em></p><h3>Why we chose it</h3><p>We chose it for the opposite reason we chose Selection Sort. It’s <strong>predictable</strong>.</p><p>It doesn’t search for a minimum, it doesn’t depend on a chunk size, and it doesn’t care how the numbers are arranged. For any input of the same size, it does the same number of passes.</p><p>That makes it a safe choice for big inputs, where Selection Sort would be too expensive.</p><h3>Why we don’t just use Radix every time</h3><p>We expected Radix to win everywhere, because on paper it’s the “fastest” algorithm. It has the best growth rate of the three, around n log n.</p><p>But when we tested 100 numbers, Selection Sort sometimes used <strong>fewer moves</strong> than Radix.</p><p>The reason is <strong>disorder</strong>.</p><h3>What disorder is</h3><p>Disorder is a number between 0 and 1 that says how far the input is from being sorted.</p><ul><li>0 means already sorted.</li><li>1 means completely reversed.</li><li>A random shuffle is around 0.5.</li></ul><p>We calculate it by looking at every pair of numbers and counting the “wrong” ones, where the bigger number comes first:</p><p><strong>Disorder = wrong pairs / total pairs</strong></p><p>For example, 1 2 3 5 4 has only one wrong pair (5 and 4) out of 10 pairs, so its disorder is 0.1. The numbers are almost sorted.</p><pre>compute_disorder(A):<br>    wrong = 0<br>    total = 0</pre><pre>    for each element x in A:<br>        for each element y after x in A:<br>            total = total + 1</pre><pre>            if x &gt; y:<br>                wrong = wrong + 1</pre><pre>    if total == 0:<br>        return 0</pre><pre>    return wrong / total</pre><h3>What each algorithm does with a low-disorder input</h3><p><strong>Selection Sort adapts.</strong> If the 100 numbers are nearly sorted, the minimum is on top, or very close to it, in every round. So a round costs almost nothing: zero or one rotation, one push to B, and one push back at the end. That’s roughly 2 moves per number, so around 200 moves for 100 numbers.</p><p><strong>Radix ignores the input.</strong> It does all its passes whether the numbers are sorted or not. For 100 numbers, that’s about 1,000 moves, even for an input that was already almost sorted. It has no way to notice that there’s nothing to do.</p><p>So with low disorder, the elements are nearly sorted, Selection Sort barely has to work, and Radix pays its full price anyway. That’s the whole reason Selection Sort wins on our 100-number tests.</p><h3>What happens when the disorder is high</h3><p>The story flips.</p><p>If the numbers are shuffled, the minimum is far from the top in almost every round, and Selection Sort pays a long rotation each time. Its number of moves grows like n².</p><p>Radix keeps the same fixed cost and becomes the better choice. Chunk Sort sits in the middle: it depends little on the order, and its moves grow like n√n.</p><p>InputSelectionChunkRadixLow disorderVery cheap, about 2nMediumFixed cost, highMedium disorderGets expensiveGood balanceFixed costHigh disorderAbout n², too expensiveAbout n√nAbout n log n, best</p><p>No algorithm is the best everywhere.</p><p><strong>The input decides.</strong></p><h3>Our fourth idea: Choose the algorithm from the disorder</h3><p>Once we understood that, the next step felt obvious. Why not measure the disorder first, then pick the algorithm that suits it?</p><p>Our current thresholds are:</p><ul><li>Disorder below 0.2: Selection Sort.</li><li>Disorder between 0.2 and 0.5: Chunk Sort.</li><li>Disorder of 0.5 or above: Radix Sort.</li></ul><pre>push_swap(A, B):<br>    disorder = compute_disorder(A)</pre><pre>    if disorder &lt; 0.2:<br>        selection_sort(A, B)</pre><pre>    else if disorder &lt; 0.5:<br>        chunk_sort(A, B)</pre><pre>    else:<br>        radix_sort(A, B)</pre><p>These thresholds are not final. We’re still testing values to find where the curves cross, and we’ll adjust them once we have real move counts for each algorithm at different disorder levels.</p><h3>The problem we still have: Moves or time complexity?</h3><p>This is the part we’re honestly not sure about, so we gave it its own section.</p><p>When we talk about the <strong>complexity</strong> of our algorithms, there are two different things we could mean, and we kept mixing them up:</p><ul><li><strong>Moves (operation count):</strong> How many instructions our program prints. This is what the subject limits (700 for 100 numbers, 5,500 for 500) and what the score is based on.</li><li><strong>Time complexity:</strong> How long our program takes to run as the input grows. This is about the work inside the code, not the instructions it prints.</li></ul><p>Let’s take Selection Sort. Its moves grow like n² in the worst case, and its running time also grows like n², because we scan A every round to find the minimum, but for a different reason.</p><p>For Radix, both measures are close to n log n, because every operation is a constant-time push or rotate and checking a bit costs nothing.</p><p>So the question we can’t answer yet is:</p><p><strong>When someone evaluates our project and asks about complexity, do they mean moves or time?</strong></p><p>Our guess is moves, because that’s what the subject limits and what the score depends on. But we don’t want to assume.</p><p>A program that prints few instructions but takes forever to run is also a bad solution, and a good answer should hold up for both.</p><p>Here’s our plan:</p><ol><li>Read the <strong>fiche de correction</strong> carefully and see exactly how complexity is asked.</li><li>See what the evaluator really checks: the number of printed instructions, the complexity of the code, or both.</li><li>Adapt after that. If it’s moves, we focus on reducing the instruction count. If it’s time, we remove the full scans, for example by tracking the next maximum instead of searching for it every round.</li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f5d337327a0b" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>