Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Insertion sort better than Bubble sort?

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 of O(N^2).

I did found some related articles, but I can't understand them.

Would anyone mind explaining it in a simple way?

like image 291
Jonathan Avatar asked May 03 '12 09:05

Jonathan


People also ask

Why is insertion sort more efficient than bubble sort?

Bubble sort is the simplest stable in-place sorting algorithm and very easy to code. Insertion sort makes fewer comparisons compared to the other two algorithms and hence is efficient where comparison operation is costly.

Which sorting algorithm is better than bubble sort?

Insertion Sort is a simple comparison based sorting algorithm. It inserts every array element into its proper position.

Why is insertion sort better?

Insertion sort has a fast best-case running time and is a good sorting algorithm to use if the input list is already mostly sorted. For larger or more unordered lists, an algorithm with a faster worst and average-case running time, such as mergesort, would be a better choice.


2 Answers

The advantage of bubblesort is in the speed of detecting an already sorted list:

BubbleSort Best Case Scenario: O(n)

However, even in this case insertion sort got better/same performance.

Bubblesort is, more or less, only good for understanding and/or teaching the mechanism of sortalgorithm, but wont find a proper usage in programming these days, because its complexity

O(n²)

means that its efficiency decreases dramatically on lists of more than a small number of elements.

like image 181
Ben Win Avatar answered Sep 25 '22 16:09

Ben Win


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.

like image 26
Victor Sorokin Avatar answered Sep 24 '22 16:09

Victor Sorokin