Stop teaching bubble sort.
[1] - https://en.wikipedia.org/wiki/Sorting_network#Insertion_and_...
Stop teaching bubble sort.
[1] - https://en.wikipedia.org/wiki/Sorting_network#Insertion_and_...
This is not the case when insertion sort is expressed as a sorting network. Take a look at this image [1]: the final "insert" has comparators that go through the entire network. The "algorithm" version wouldn't do that: it would stop (using a branch) as soon as the entry hits the correct place. If you remove that branch (which, remember, is the thing that makes insertion sort faster in the general case), insertion and bubble sort are indeed very similar.
The point here is that "sorting algorithms" and "sorting networks" are not the same thing: a sorting algorithm can branch, a sorting network cannot. The same principles of bubbling and insertion can apply to both, but that does not mean that an insight that applies to sorting networks necessarily applies to sorting algorithms.
[1]: https://en.wikipedia.org/wiki/Sorting_network#/media/File:Re...
(PS: I actually wrote most of that wikipedia article years ago! I did the illustrations too! I basically just wrote down and made diagrams for whatever I could understand from The Art of Computer Programming vol 3. The insight about how bubble sort and insertion sort are essentially the same when expressed as sorting network is from Knuth, though I doubt it's original with him)
In particular, the author claims (and presents benchmarks that appear to verify) that for sorting very small arrays, bubblesort is better than insertion sort because you can do it with fewer unpredictable branches, and unpredictable branches are very bad for performance.
Maybe the same optimizations can be applied to insertion sort, but it's not obvious to me that they can; in particular, the inner loop of insertion sort is of variable length and necessarily involves a hard-to-predict branch. You could do away with that by always going all the way to the end of the array, but unless I'm confused this gives you an algorithm pretty much equivalent to bubblesort, and equally worthy (according to the usual sorts of analysis) of being called "usually the worst in every conceivable way".
On very small arrays bubble sort is faster than quicksort as quicksort has a large constant overhead.
Constant overheads are usually disregarded in complexity analysis but in practice, it can be significant.
Question: Does it always do less swaps? Probably yes, I think.
> Most contemporary implementations of quicksort use Hoare partition, for obvious reasons: it does as many comparisons as the Lomuto partition and fewer swaps.
> Given that Hoare partition clearly does less work than Lomuto partition, the question would be why ever teach or use the latter at all. […] implemented in a branch-free manner, Lomuto partition is a lot faster than Hoare partition on random data.
I still dont know why quicksort is so common given its worst case performance.