Why is bubble sort slower than insertion sort if they’re both O(n²)?
My notes say both bubble sort and insertion sort are O(n²) in the worst case, but insertion sort seems to run faster in practice. Why?
My notes say both bubble sort and insertion sort are O(n²) in the worst case, but insertion sort seems to run faster in practice. Why?
Big O only describes how the work grows, not the constant amount of work per step. Bubble sort makes many swaps, each three moves, while insertion sort shifts items along and drops each one in place, so it does less work per pass. On nearly sorted data insertion sort finishes in close to n steps, which makes it noticeably faster in practice.
Accepted answer
Same big-O class, but different constants and behaviour. Bubble sort repeatedly swaps adjacent elements even when the list is nearly sorted, while insertion sort does fewer comparisons and shifts on partially sorted data, often stopping early. So in practice, especially on mostly-sorted lists, insertion sort tends to do noticeably less work.