54

Do bubble sorts have any real world use? Every time I see one mentioned, it's always either:

  1. A sorting algorithm to learn with.
  2. An example of a sorting algorithm not to use.
Grokify
  • 15,092
  • 6
  • 60
  • 81
Jason Baker
  • 192,085
  • 135
  • 376
  • 510

16 Answers16

87

Bubble sort is (provably) the fastest sort available under a very specific circumstance. It originally became well known primarily because it was one of the first algorithms (of any kind) that was rigorously analyzed, and the proof was found that it was optimal under its limited circumstance.

Consider a file stored on a tape drive, and so little random access memory (or such large keys) that you can only load two records into memory at any given time. Rewinding the tape is slow enough that doing random access within the file is generally impractical -- if possible, you want to process records sequentially, no more than two at a time.

Back when tape drives were common, and machines with only a few thousand (words|bytes) of RAM (of whatever sort) were common, that was sufficiently realistic to be worth studying. That circumstance is now rare, so studying bubble sort makes little sense at all -- but even worse, the circumstance when it's optimal isn't taught anyway, so even when/if the right situation arose, almost nobody would realize it.

As far as being the fastest on an extremely small and/or nearly sorted set of data, while that can cover up the weakness of bubble sort (to at least some degree), an insertion sort will essentially always be better for either/both of those.

Jerry Coffin
  • 476,176
  • 80
  • 629
  • 1,111
  • 2
    But if you could spare an extra tape, a merge sort would still beat it. – Mark Ransom Jul 11 '11 at 22:27
  • 3
    @Mark: Oh yes -- loosen almost *any* of the restrictions, and Bubblesort will nearly always lose, and usually quite badly. – Jerry Coffin Jul 11 '11 at 22:39
  • Could you please explain the your tape drive example in a bit more detail? – gen Dec 03 '13 at 18:08
  • @gen: I'm not sure what to add. What do you find unclear? – Jerry Coffin Dec 03 '13 at 18:26
  • 7
    @gen I believe the defining limitation is this: bubble sort is good when sequential access is much faster than random access, and you can only keep two objects in memory. With a tape drive, it's *mechanically* already moving sequentially, so you might as well do as much work as you can while it's doing it, without slowing/stopping/reversing the tape machine. – kibibu Dec 10 '13 at 00:05
  • Isn't cocktail sort better for that purpose? – Xwtek Aug 15 '18 at 03:00
  • @Akangka: It's only even a decent candidate if you can read the tape backwards, which wasn't in the original spec. If you can read backwards (without any penalty) it can be an improvement. – Jerry Coffin Aug 15 '18 at 03:29
  • Wouldn't insertion sort still be better in such case? – Hedede Jan 03 '19 at 18:53
  • @Hedede: When you can read the tape backwards? Yes, probably. – Jerry Coffin Jan 03 '19 at 18:55
50

It depends on the way your data is distributed - if you can make some assumptions.

One of the best links I've found to understand when to use a bubble sort - or some other sort, is this - an animated view on sorting algorithms:

http://www.sorting-algorithms.com/

Matthew Scharley
  • 127,823
  • 52
  • 194
  • 222
Remy Sharp
  • 4,520
  • 3
  • 23
  • 40
20

It doesn't get used much in the real world. It's a good learning tool because it's easy to understand and fast to implement. It has bad (O(n^2)) worst case and average performance. It has good best case performance when you know the data is almost sorted, but there are plenty of other algorithms that have this property, with better worst and average case performance.

Bill the Lizard
  • 398,270
  • 210
  • 566
  • 880
  • 11
    I actually find it amazing that bubble sort is (often) taught before insertion or selection sort. Both those I find to be incredibly intuitive. Unless I'm mistaken, most people do one or the other when sorting a playing cards. Bubble sort requires a little more thought. – Thomas Eding Oct 10 '11 at 22:26
  • 1
    This is very old but I thought I would throw in 5 cents for anyone who come across this 4 upvoted comment. You are right on insertion on selection sort being more intuitive than trying to make a student see a bubble floating in a vector. However, if students have little experience in programming, a 4 line of code is easier to explain *mapping* from code to visualization or abstraction. Many concepts from the bubble invariant can move along to, say, an insertion Sort. For instance, the idea of a frontier moving along the first loop dividing the array in ordered and yet to be ordered. – Oeufcoque Penteano Dec 22 '13 at 21:28
  • Insertion sort is both more intuitive and more practical than other O(n^2) average case sorting algorithm. In fact, for small lists, it is THE fastest algorithm. And people also use that to sort cards, too. – Xwtek Aug 15 '18 at 03:06
  • To add to comment. From how I learned it, Bubble sort, Selection sort, and Insertion sort are similar; All O(N^2) worst case, but each a little better than the next. So Bubble sort being the worst, you can see how it can be improved upon little by little, with Insertion sort(when partially sorted under normal conditions) being twice as fast as Bubble sort, and a little better than Selection sort. Insertion sort is taught before Quicksort as it is used at the end of Quicksort. Bubble sort = O(n^2) time for comparisons and swapping, Selection sort = O(n^2) for comparisons, but O(n) for swapping. – eaglei22 Apr 11 '19 at 22:33
11

I came across a great use for it in an optimisation anecdote recently. A program needed a set of sprites sorted in depth order each frame. The spites order wouldn't change much between frames, so as an optimisation they were bubble sorted with a single pass each frame. This was done in both directions (top to bottom and bottom to top). So the sprites were always almost sorted with a very efficient O(N) algorithm.

workmad3
  • 25,101
  • 4
  • 35
  • 56
  • 7
    Actually insertion sort is still better for this. A lot of real time rendering systems use insertion sort for very large lists of things, for the reason that things tend to be "almost" ordered for each frame. Bubble sort is very similar though. – TM. Nov 09 '08 at 22:55
  • 2
    @TM I believe you missed the bit where it's *two fixed passes per frame*. It will eventually be sorted, but it might take a few (hundred) frames. A single pass of insertion sort per frame will make sure the first (or last) item is in the right spot. A bubble will make all the sprites move towards their correct spot. – kibibu Dec 10 '13 at 00:09
7

It's probably the fastest for tiny sets.

Speaking of education. A link to the last scene of sorting out sorting, it's amazing. A must-see.

Cristian Libardo
  • 9,260
  • 3
  • 35
  • 41
3

It's good for small data sets - which is why some qsort implementations switch to it when the partition size gets small. But insertion sort is still faster, so there's no good reason to use it except as a teaching aid.

The Archetypal Paul
  • 41,321
  • 20
  • 104
  • 134
3

we recently used bubblesort in an optimality proof for an algorithm. We had to transform an arbitrary optimal solution represented by a sequence of objects into a solution that was found by our algorithm. Because our algorithm was just "Sort by this criteria", we had to prove that we can sort an optimal solution without making it worse. In this case, bubble sort was a very good algorithm to use, because it has the nice invariant of just swapping two elements that are next to each other and are in the wrong order. Using more complicated algorithms there would have melted brains, I think.

Greetings.

Tetha
  • 4,826
  • 1
  • 16
  • 17
2

I think it's a good "teaching" algorithm because it's very easy to understand and implement. It may also be useful for small data sets for the same reason (although some of the O(n lg n) algorithms are pretty easy to implement too).

Jay Conrod
  • 28,943
  • 19
  • 98
  • 110
2

I can't resist responding to any remarks on bubble sort by mentioning the faster (seems to be O(nlogn), but this is not really proven) Comb Sort. Note that Comb sort is a bit faster if you use a precomputed table. Comb sort is exactly the same as bubble sort except that it doesn't initially start by swapping adjacent elements. It's almost as easy to implement/understand as bubble sort.

Brian
  • 25,523
  • 18
  • 82
  • 173
2

Bubble sort is easy to implement and it is fast enough when you have small data sets.

Bubble sort is fast enough when your set is almost sorted (e.g. one or several elements are not in the correct positions), in this case you better to interlace traverses from 0-index to n-index and from n-index to 0-index. Using C++ it can be implemented in the following way:

void bubbleSort(vector<int>& v) { // sort in ascending order
  bool go = true;
  while (go) {
    go = false;
    for (int i = 0; i+1 < v.size(); ++i)
      if (v[i] > v[i+1]) {
         swap(v[i], v[j]);
         go = true;
      }
    for (int i = (int)v.size()-1; i > 0; --i) 
      if (v[i-1] > v[i]) {
         swap(v[i-1], v[i]);
         go = true;
      }
  }
}

It can be good if swap of two adjacent items is chip and swap of arbitrary items is expensive.

Donald Knuth, in his famous "The Art of Computer Programming", concluded that "the bubble sort seems to have nothing to recommend it, except a catchy name and the fact that it leads to some interesting theoretical problems".

Since this algorithm is easy to implement it is easy to support, and it is important in real application life cycle to reduce effort for support.

sergtk
  • 10,714
  • 15
  • 75
  • 130
1

It is the sort I use most often actually. (In our project, we cannot use any external libraries.)

It is useful when I know for sure that data set is really small, so I do not care one bit about speed and want shortest and simplest code.

Bubble is not the lowest you can go. Recently, I was in a situation when I needed to sort exactly three elements. I wrote something like this:

// Use sort of stooge to sort the three elements by cpFirst

SwapElementsIfNeeded(&elementTop, &elementBottom);
SwapElementsIfNeeded(&elementTop, &elementMiddle);
SwapElementsIfNeeded(&elementMiddle, &elementBottom);

*pelement1 = elementTop;
*pelement2 = elementMiddle;
*pelement3 = elementBottom;
buti-oxa
  • 11,261
  • 5
  • 35
  • 44
1

I used to use it in some cases for small N on the TRS-80 Model 1. Using a for loop, one could implement the complete sort on one program line.

Other than that, it is good for teaching, and sometimes for lists that are nearly in sorted order.

EvilTeach
  • 28,120
  • 21
  • 85
  • 141
1

I once used it for a case where the vast majority of the time it would be sorting two items.

The next time I saw that code, someone had replaced it with the library sort. I hope they benchmarked it first!

Mark Ransom
  • 299,747
  • 42
  • 398
  • 622
  • sorting two items? `(a < b)? (swap):(do-not-swap)`? – Lazer Jul 18 '10 at 04:51
  • 1
    @Lazer, although the majority of the time it was 2, it still had to handle the case where there were more than 2. In retrospect I could have treated that as two different cases with different code to handle each, and I've been advised that the library sorts generally work this way anyway. – Mark Ransom Jul 18 '10 at 04:57
1

It's quick and easy to code and (nearly impossible to do wrong). It has it's place if you're not doing heavy lifting and there's no library sorting support.

Brian Knoblauch
  • 20,639
  • 15
  • 57
  • 92
1

Oh yes, it is a good selection mechanism. If you find it in code written by someone, you don't hire him.

Stephan Eggermont
  • 15,847
  • 1
  • 38
  • 65
  • 2
    Even if it works perfect in specific suituation? – pierrotlefou Nov 14 '09 at 06:20
  • 2
    Yes. If you can tune the situation so that bubblesort is the perfect answer, you should have been able to tune the situation so that it isn't. – Stephan Eggermont Nov 15 '09 at 09:55
  • 1
    haha, I have already used this criteria to reject candidate :) – sergtk Dec 06 '09 at 09:48
  • Incredible, how many negative votes this gets... – Stephan Eggermont Jan 17 '10 at 11:26
  • 5
    @Stephan: It gets negative votes (including mine) because blanket rules like that aren't just silly, they're downright _wrong_. Bubblesort takes very few instructions while in many cases being "fast enough". I certainly wouldn't hire anyone for an embedded project that couldn't envision those properties being useful. – Nicholas Knight Jul 18 '10 at 02:53
  • I find it works pretty well. In real life the reason it is used is because they don't know their algorithms. – Stephan Eggermont Jul 18 '10 at 21:40
  • I agree with Nicholas. Blanket rules do not help people. If a module is functionally correct, well organized, documented, and serviceable yet uses a bubble sort instead of a quicksort that does not mean that the person is inherently subhuman scum. – Skrylar Aug 19 '13 at 19:23
  • It is an indicator for lack of craftmanship. We have enough bad code – Stephan Eggermont Sep 06 '13 at 21:01
  • 1
    @StephanEggermont I've written a bubblesort in C++ templates for sorting numeric arrays of fixed lengths (<10). Quicksort was *much* slower. Know the purpose of the code. – kibibu Dec 10 '13 at 00:15
  • @kibibu so you know how to write bad code but still don't know your algorithms. I don't want to work with you. – Stephan Eggermont Jan 03 '14 at 15:23
0

Mostly nothing. Use QuickSort or SelectionSort instead...!

Thomas Hansen
  • 5,523
  • 1
  • 23
  • 28