Stalin Sort: The Sorting Algorithm That Purges Dissent
In the glorious world of computer science, we have many elegant ways to sort data — quicksort, mergesort, heapsort. They compare, they…
In the glorious world of computer science, we have many elegant ways to sort data — quicksort, mergesort, heapsort. They compare, they swap, they do complex dances of logic.
But sometimes, order is not achieved through negotiation. Sometimes, it’s achieved through fear.
Enter Stalin Sort, the only algorithm that doesn’t bother fixing the wrong elements. It simply removes them from existence.
If a number doesn’t follow the leader, it’s off to the digital Gulag. The result? A list that is, by definition, sorted. (Mostly because the troublemakers aren’t around to argue.)
The Code of Iron Fist
Lets see stalin sort in practice! save the following file as stalin_sort.py
#!/usr/bin/env python3
def stalin_sort(seq):
if not seq:
return []
result = [seq[0]] # The glorious first element
for x in seq[1:]:
if x >= result[-1]:
result.append(x) # Loyal element joins the parade
# else: element disappears mysteriously at 3 AM
return result
# Demonstration
numbers = [5, 3, 4, 8, 6, 7, 9]
print("Original:", numbers)
print("Stalin-sorted:", stalin_sort(numbers))Making the file executable:
chmod +x ./stalin_sort.pyOutput:
./stalin_sort.py
Original: [5, 3, 4, 8, 6, 7, 9]
Stalin-sorted: [5, 8, 9]How it works
Stalin sort works by iterating through a list once and keeping only the elements that are in non-decreasing order compared to the last accepted element. Anything that “breaks the order” is simply removed.
Given a list of
5, 3, 4, 8, 6, 7, 9- Start with the first element
5. Keep it.
→ result:[5] - Next is
3. Since3 < 5, it is “out of order” → remove it.
→ result:[5] - Next is
4. Since4 < 5, remove it too.
→ result:[5] - Next is
8. Since8 >= 5, keep it.
→ result:[5, 8] - Next is
6. Since6 < 8, remove it.
→ result:[5, 8] - Next is
7. Since7 < 8, remove it.
→ result:[5, 8] - Next is
9. Since9 >= 8, keep it.
→ result:[5, 8, 9]
Final list:
5, 8, 9Why this always “works”
The algorithm ensures that each new element added is ≥ the last one kept. That means the final sequence is always sorted. It never fixes order violations; it erases them.
- Complexity: O(n) — single pass, no swaps.
- Downside: You lose data.
- Upside: You always end up with a sorted list.
Final Thoughts
Stalin Sort is not technically a sorting algorithm — it’s more like a political purge in list form. It guarantees that what remains is sorted… because anything that isn’t sorted is no longer there.
It’s inefficient for most purposes but brutally effective if you care only about order and not about casualties.
Remember: in Stalin Sort, all lists are sorted — some just have fewer citizens left to tell the tale.