Insertion sort better than Bubble sort?

后端 未结 5 1894
佛祖请我去吃肉
佛祖请我去吃肉 2021-01-17 18:50

I am doing my revision for the exam.

Would like to know under what condition will Insertion sort performs better than bubble sort given same average case complexity

5条回答
  •  不知归路
    2021-01-17 19:43

    Following things came to my mind:

    1. Bubble sort always takes one more pass over array to determine if it's sorted. On the other hand, insertion sort not need this -- once last element inserted, algorithm guarantees that array is sorted.

    2. Bubble sort does n comparisons on every pass. Insertion sort does less than n comparisons: once the algorithm finds the position where to insert current element it stops making comparisons and takes next element.

    3. Finally, quote from wikipedia article:

    Bubble sort also interacts poorly with modern CPU hardware. It requires at least twice as many writes as insertion sort, twice as many cache misses, and asymptotically more branch mispredictions. Experiments by Astrachan sorting strings in Java show bubble sort to be roughly 5 times slower than insertion sort and 40% slower than selection sort

    You can find link to original research paper there.

提交回复
热议问题