5 ms·
bubble sort is useful for two cases: you have a small (3-5) fixed size array that you need to sort with very simple code. A classic case is to enforce a defin
by nn3 13y ago
bubble sort is useful for two cases:
you have a small (3-5) fixed size array that you need to sort with very simple code.
A classic case is to enforce a defined lock ordering when you have more than two locks in dynamic objects that you all need to acquire. In this case open coded bubble sort is good and beats calling a complicated library function.
The other case is your objects are known to be nearly already sorted. In this case bubble sort is a very good algorithm too (although it may be better to avoid a full sort then)
In short bubble sort is often a good choice when anything else would be over engineered.
To expand on this point: simplicity ("just do what you need") is often under valued.
One simple data structure trick I learned recently (from Knuth) is: people often use complicated balanced tree libraries like b or rb. You only need a balanced tree library when the sort keys are in-balanced. One simple trick is to hash the input keys. As long as your hash function is good enough, the keys will be already spread out and you can then use a much simpler non balanced tree.
- jeltz 13y agoInsertion sort is almost always faster than bubble sort and just as easy to implement, so no there is no reason to implement bubble sort that I know of.
- Millennium 13y agoIf you already have a list of objects, then bubble sort can beat insertion sort in terms of space, because it doesn't have to construct a second list. That's pretty much the only place left where bubble sort has any advantage, but when you need it, nothing else will do.
- jeltz 13y agoInsertion sort does swap elements in place so requires zero additional memory. It is like bubble sort but with better good cases and is as easy to implement. I recommend reading the Wikipedia article about it. http://en.wikipedia.org/wiki/Insertion_sort http://en.wikipedia.org/wiki/Insertion_sort
- Millennium 13y agoIt swaps elements in place in the list it builds, but it requires building another list. Bubble sort doesn't.