Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is a bubble sort good for? [closed]

Do bubble sorts have any real world use? Every time I see one mentioned, it's always either:

  1. A sorting algorithm to learn with.
  2. An example of a sorting algorithm not to use.
like image 461
Jason Baker Avatar asked Nov 09 '08 16:11

Jason Baker


People also ask

What is bubble sort best for?

Bubble sort is a simple sorting algorithm used to rearrange a set of elements in ascending or descending order. It's useful for smaller sets of elements but is inefficient for larger sets.

When should you not use bubble sort?

Avoid using bubble sort when:The array to be sorted has a large number of elements. The array is completely unsorted. You want a faster run time and memory is not a concern.

Is bubble sort ever useful?

Bubble sort is slow enough that it is impractical to use in most real applications. Though it has an effective best-case function, it is slower than other sorting algorithms. For example, it is twice as slow as selection sorting and four times slower than insertion sort.


2 Answers

Bubble sort is (provably) the fastest sort available under a very specific circumstance. It originally became well known primarily because it was one of the first algorithms (of any kind) that was rigorously analyzed, and the proof was found that it was optimal under its limited circumstance.

Consider a file stored on a tape drive, and so little random access memory (or such large keys) that you can only load two records into memory at any given time. Rewinding the tape is slow enough that doing random access within the file is generally impractical -- if possible, you want to process records sequentially, no more than two at a time.

Back when tape drives were common, and machines with only a few thousand (words|bytes) of RAM (of whatever sort) were common, that was sufficiently realistic to be worth studying. That circumstance is now rare, so studying bubble sort makes little sense at all -- but even worse, the circumstance when it's optimal isn't taught anyway, so even when/if the right situation arose, almost nobody would realize it.

As far as being the fastest on an extremely small and/or nearly sorted set of data, while that can cover up the weakness of bubble sort (to at least some degree), an insertion sort will essentially always be better for either/both of those.

like image 108
Jerry Coffin Avatar answered Oct 11 '22 20:10

Jerry Coffin


It depends on the way your data is distributed - if you can make some assumptions.

One of the best links I've found to understand when to use a bubble sort - or some other sort, is this - an animated view on sorting algorithms:

http://www.sorting-algorithms.com/

like image 29
Remy Sharp Avatar answered Oct 11 '22 21:10

Remy Sharp