Community
Computer Science Solved

Why is bubble sort slower than insertion sort if they’re both O(n²)?

DSDev ShahMentorasked 5 days ago

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?

#sorting-algorithms

Saki’s answer

Confidence: High

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.

From the lesson Sorting Algorithms

1 answer

  • ARMs. Ananya Rao Verified teacherLuminary4 days ago

    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.

Helper· 88

0 / 2000