
These factors make bubble sort much slower in general than insertion sort. With bubble sort, branching is essentially random, and we can expect a branch miss half the time! With every single compare! This means bubble sort is bad for pipelined processors if comparisons and swaps are relatively cheap/fast. We do a linear search at the same time as a linear insert, and we can generally predict/assume that the linear search/insert will continue until the correct space is found. This means bubble sort is bad if comparisons are expensive/slow.Īlso, the branching associated with swaps and compares for insertion sort is more predictable. With bubble sort, we are always comparing EVERY pair in the unsorted sublist with each pass, so that's n-m comparisons (twice as many as insertion sort on random data). With random data, you can expect to make m/2 comparisons and swaps, where m is the size of the sorted sublist. With insertion sort, we are only performing a linear search in the sorted sublist with each pass. However, insertion sort will perform fewer comparisons in general. Yes, after each pass, insertion sort and bubble sort intuitively seem the same - they both build a sorted sublist at the edge. I will try to give a more concise and informative answer than others. In insertion sort elements are bubbled into the sorted section, while in bubble sort the maximums are bubbled out of the unsorted section. Note that typical implementations terminate early if no swaps are made during one of the iterations of the outer loop (since that means the array is sorted). The 5 is bubbled out of the unsorted section In each iteration, sift through the unsorted section to find the maximum. In each iteration the next element is bubbled through the sorted section until it reaches the right spot: sorted | unsortedĪfter i iterations the last i elements are the biggest, and ordered. The best reason I think you could give to justify this would go something like this (but still be largely unconvincing): By first scanning the entire list before locating the exact pair of numbers t.

After i iterations the first i elements are ordered. Answer (1 of 6): Whos saying its better I dont know anyone who says its meaningfully better.
