When would you ever want bubblesort? (2023)
by atan2 on 12/10/2025, 9:45:11 PM
https://buttondown.com/hillelwayne/archive/when-would-you-ever-want-bubblesort/
Comments
by: Syzygies
When I was a senior at Swarthmore College, Herb Wilf came over from U Penn to teach a course in combinatorial algorithms. I was encouraged to attend.<p>He claimed that choosing a subset of k integers at random from {1..n} should have a log in its complexity, because one needs to sort to detect duplicates. I realized that if one divided [1..n] into k bins, one could detect duplicates within each bin, for a linear algorithm. I chose bubble sort because the average occupancy was 1, so bubble sort gave the best constant.<p>I described this algorithm to him around 5pm, end of his office hours as he was facing horrendous traffic home. I looked like George Harrison post-Beatles, and probably smelled of pot smoke. Understandably, he didn't recognize a future mathematician.<p>Around 10pm the dorm hall phone rang, one of my professors relaying an apology for brushing me off. He got it, and credited me with many ideas in the next edition of his book.<p>Of course, I eventually found all of this and more in Knuth's books. I was disillusioned, imagining that adults read everything. Later I came to understand that this was unrealistic.
12/11/2025, 4:01:52 AM
by: addaon
The article, and many of the responses, are hinting at the fact that bubblesort is an example of an anytime algorithm. This is a wide class of algorithms which provide a correct answer after some amount of time, but provide an increasingly good answer in increasing amounts of time short of the completion time. This is a super valuable property for real time systems (and many of the comments about games and animations discuss that). The paper that introduced me to the category is "Anytime Dynamic A*" [0], and I think it's both a good paper and a good algorithm to know.<p>[0] <a href="https://cdn.aaai.org/ICAPS/2005/ICAPS05-027.pdf" rel="nofollow">https://cdn.aaai.org/ICAPS/2005/ICAPS05-027.pdf</a>
12/11/2025, 1:23:55 AM
by: zeta0134
I used bubblesort on purpose in a game project. Specifically, to sort sprites in an NES game back to front, lazily, spending as few CPU cycles as possible. Bubblesort on the very small list (a dozen objects max), and early exit after the first swap. It <i>eventually</i> completes, and that was just fine. It's tiny, incredibly simple, and somewhat resilient to the list changing from frame to frame as objects spawn and despawn. Each partial sort makes some progress no matter what.<p>A few other algorithms would have fit the bill just as well, but bubblesort is perfectly adequate, so that's what will likely ship. More complex algorithms end up losing out due to greater initial overhead or larger ROM size.
12/10/2025, 10:49:42 PM
by: mhandley
I've used bubblesort when simulating LEO satellite constellations, calculating which satellite is closest to a location. I used one single backwards pass of bubblesort, so O(n) every k timesteps to bring the closest to the head of the array, then every timestep just do one backwards bubblesort pass over the first few in the array. Given satellites move smoothly, if you initialize right (a few full passes at the start to get the closest few at the front) and get the constants right so a satellite outside the front few in the array can't have moved far enough to become closest without being promoted to the front few by a periodic full pass, then you always maintain the closest at the front of the array very cheaply. And this has the advantage of also being very simple to code.
12/10/2025, 11:15:28 PM
by: bxparks
On 8-bit and 32-bit microcontrollers (e.g. 8-bit AVR, 32-bit ESP8266/ESP32), Insertion sort is 6X faster than Bubble Sort on random data. I have tested this up to about N=1000.<p>Both Insertion sort and Bubble sort are O(N^2). Both are stable sorts. Insertion sort consumes only about 10-20 bytes more flash memory than Bubble sort. It's hard to think of situations where Bubble sort would be preferred over Insertion sort.<p>Shell sort is vastly superior if you can afford an extra 40-100 bytes of flash memory. (It's not too much more complicated than Insertion sort, but sometimes, we don't have 100 extra bytes.) It is O(N^k), where k ≈ 1.3 to 1.5. As soon as N ⪆ 30, Shell sort will start clobbering Insertion sort. For N ≈ 1000, Shell sort is 10X faster than Insertion sort, which in turn is 6X faster than Bubble sort. Unfortunately Shell sort is not stable.<p>Comb sort has a similar O(N^k) runtime complexity as Shell sort. But it seems slower than Shell sort by a constant factor. Comb sort is also not stable. I cannot think of any reason to use Comb sort over Shell sort.<p>Quick sort is not much faster than Shell until about N ≈ 300. Above that, the O(N*log(N) of Quick sort wins over the O(N^k) of Shell sort. But Quick sort is not stable.<p>Merge sort is stable and runs in O(N*log(N)), but it consumes an extra O(N) of RAM, which may be impossible on a microcontroller. You may be forced back to Insertion sort for a stable sort.
12/11/2025, 1:47:15 AM
by: JKCalhoun
The appeal of bubble sort for me is that is it the only one I understand well enough to implement myself without having to think much about it.
12/11/2025, 12:42:44 AM
by: jandrewrogers
The only use I've seen is incrementally sorting large arrays during brute-force search of said arrays, since that is approximately free and brute-force search is pretty efficient and fast on modern CPUs. Set a "sorted" flag if/when the array is eventually sorted.<p>The idea was that the vast majority of arrays in a large set are not searched often enough to justify the cost of sorting them and sorting is an expensive operation if you are computing on a deadline. You also don't always know which ones will be heavily searched ahead of time. Using bubblesort, only the heavily accessed arrays end up sorted but as a side-effect of search rather than having separate heuristics to decide when/what to sort.
12/10/2025, 10:45:45 PM
by: johnnyanmac
Yeah, the article beat me to the gamedev example. Bubble sort being able to always "soft sort" on every iteration makes it the easiest to suspend and resume when you have a lot of other work to do, and when sorting is low priority.<p>Also, general wisdom to be mindful of data sizes and cache coherency. O(NLogN) vs. O(N^2) doesn't mean much when you're only sorting a few dozen items. Meanwhile, O(N) space can have drastic performance hitches when reallocating memory.
12/11/2025, 1:06:17 AM
by: nick__m
<p><pre><code> if you apply quicksort to 2^20 random integers, at some point you're sorting 2^17 8-integer subpartitions </code></pre> why not use an 8 wide optimal sort network for those 8 integers?
12/10/2025, 10:16:34 PM
by: jaw0
at a previous workplace, every new hire would discover the handwritten bubblesort in our codebase, freak out, and submit a pull request to fix it.<p>and every new hire got taken to the whiteboard to learn about sort algorithm performance: bubblesort is O(n) in the best case.<p>and in our codebase, the data being sorted fit that best case (the data was already sorted or almost sorted).
12/11/2025, 4:42:24 AM
by: zitterbewegung
Related to this is Timsort which combines merge sort and insertion sort <a href="https://en.wikipedia.org/wiki/Timsort" rel="nofollow">https://en.wikipedia.org/wiki/Timsort</a>
12/10/2025, 10:35:18 PM
by: another_twist
When the array is almost sorted. Bubble sort complexity is linear + inversions so if the inversions are low (the more sorted the array the lower the number of inversions), bubble sort is close to a linear pass.
12/11/2025, 9:51:28 AM
by: dspillett
For small sets, or small-ish sets when you are coding quick, don't have a convenient standard library sort to hand, and are prioritising correctness over absolute performance.<p>Though in reality almost never: you almost always have a convenient built-in sort that is as quick & easy to use (likely quicker & easier), and in circumstances where the set is small enough for bubblesort to be just fine, the speed, memory use, or other properties of what-ever other sort your standard library uses aren't going to be a problem either.<p>As others have pointed out, sometimes it is useful for partial sorts due to the “always no less sorted than before at any point in the process (assuming no changes due to external influence)” property.<p>wrt:<p><i>> If you make each frame of the animation one pass of bubblesort, the particles will all move smoothly into the right positions. I couldn't find any examples in the wild,</i><p>There are <i>hundreds</i> of sort demos out there, both live running and on publicly hosted videos, that show the final positions by hue, getting this effect. Seems odd that they couldn't find a single one.<p>EDIT: actually, I can't find any of the rainbow based sort demos I was thinking of, a lot of promising links seem dead. I take back my little moan!
12/10/2025, 11:46:16 PM
by: Findecanor
I've used bubblesort in a coding interview, because it was the easiest to remember and get correct on a whiteboard in short time.-
12/11/2025, 12:18:49 AM
by:
12/10/2025, 11:33:45 PM
by: aappleby
Can confirm, have used bubble sort for incrementally sorting particles in a particle system and plants in a terrain renderer.
12/10/2025, 10:42:58 PM
by: CyLith
When sorting eigenpairs of a dense matrix, usually tou end up with a Schur decomposition. The basic operation that you can do is swap two adjacent eigenvalues on the diagonal, so bubblesort is a natural candidate.
12/11/2025, 2:44:49 AM
by: caycep
I learned this from President Obama...
12/10/2025, 10:10:33 PM
by: lucraft
It's way easier to remember and program<p>When I was playing The Farmer Was Replaced and needed to implement sorting, I just wrote a bubble sort. Worked first time.
12/11/2025, 11:47:49 AM
by: kazinator
Doesn't Shell sort also have the property of the exchanges leaving the array more ordered than before?<p><a href="https://en.wikipedia.org/wiki/Shellsort" rel="nofollow">https://en.wikipedia.org/wiki/Shellsort</a><p>Shellsort can be regarded as an improvement over either Bubble Sort or Insertion Sort.
12/11/2025, 4:22:05 AM
by: beeforpork
A: For small arrays. I would add: particularly if you need a stable sort algorithm, which is either complex (Block Sort) or uses O(n) space (Merge Sort).
12/10/2025, 10:14:48 PM
by: opensourcemaxi
bubble sort is sometimes used in information retrieval use cases for reranking top k based on some signals, especially specific to a user profile. I feel heap sort comes up as well, yet neither are necessarily the most efficient.
12/11/2025, 12:55:29 AM
by: LorenPechtel
Used it a couple of times when n was inherently very low.<p>And while I've never hit a case I would think it would have merit with data known to be pretty close to properly sorted.
12/11/2025, 2:08:05 AM
by:
12/11/2025, 1:07:36 AM
by: pilord314
When you get into C code sometimes you know the most thinngs that will be in the priority queue is like 3. So bubble sort is fine.<p>You can also do something like a calendar queue with bubble sort for each bin.
12/11/2025, 6:03:03 AM
by: whateveracct
it's great if you need to sort in the face of unreliable memory iirc
12/11/2025, 7:00:41 AM
by: ErroneousBosh
If you need a stable sort, can't be bothered finding a massive oversize library to link to, and only need to sort a relatively small number of objects on a system that's resource-constrained, I'm guessing?
12/10/2025, 11:28:58 PM
by: 13415
Well, I used Bubblesort to sort the results of lottery draws because it was very easy to implement.
12/10/2025, 10:32:29 PM
by: AnimalMuppet
In all your big-O analyses, remember: n = 3 more often than you think. n = 12 <i>a lot</i> more often than you think. If that's your case, there's nothing wrong with bubble sort unless you have very tight performance constraints.<p>Worse, big-O always hides a constant factor. What's bubblesort's constant? What's quicksort's? It wouldn't surprise me if, for small enough n (2 or 3, and maybe a bit higher), bubblesort is actually faster.<p>Note well: I have not actually benchmarked this.<p>Also note well: Determine what your n is; don't assume that it's either large or small.
12/11/2025, 2:24:03 AM
by: pestatije
to compare other sort algos against it
12/10/2025, 10:49:20 PM
by: JSR_FDED
I’ve used it when I didn’t want the hassle of another dependency
12/10/2025, 11:02:27 PM
by: 6Roman6
[dead]
12/11/2025, 3:05:41 AM