Bubble Sort
Bubble Sort
Bubble sort
From Wikipedia, the free encyclopedia
Contents
1 Analysis Class Sorting algorithm
1.1 Performance Data structure Array
1.2 Rabbits and turtles Worst case performance
1.3 Step-by-step Best case performance
example Average case performance
2 Implementation
Worst case space complexity auxiliary
2.1 Pseudocode
implementation
2.2 Optimizing bubble
sort
3 In practice
4 Variations
5 Debate over name
6 Notes
7 References
8 External links
Analysis
http://en.wikipedia.org/wiki/Bubble_sort 1/6
2/26/2015 Bubble sort - Wikipedia, the free encyclopedia
Performance
The only significant advantage that bubble sort has over most other
implementations, even quicksort, but not insertion sort, is that the An example of bubble sort. Starting from the
ability to detect that the list is sorted is efficiently built into the beginning of the list, compare every adjacent pair,
algorithm. When the list is already sorted (best-case), the complexity swap their position if they are not in the right order
of bubble sort is only O(n). By contrast, most other algorithms, even (the latter one is smaller than the former one). After
those with better average-case complexity, perform their entire each iteration, one less element (the last one) is
sorting process on the set and thus are more complex. However, not needed to be compared until there are no more
only does insertion sort have this mechanism too, but it also performs elements left to be compared.
better on a list that is substantially sorted (having a small number of
inversions).
Bubble sort should be avoided in the case of large collections. It will not be efficient in the case of a reverse-ordered
collection.
Various efforts have been made to eliminate turtles to improve upon the speed of bubble sort. Cocktail sort is a bi-
directional bubble sort that goes from beginning to end, and then reverses itself, going end to beginning. It can move
turtles fairly well, but it retains O(n2) worst-case complexity. Comb sort compares elements separated by large gaps, and
can move turtles extremely quickly before proceeding to smaller and smaller gaps to smooth out the list. Its average
speed is comparable to faster algorithms like quicksort.
Step-by-step example
Let us take the array of numbers "5 1 4 2 8", and sort the array from lowest number to greatest number using bubble sort.
In each step, elements written in bold are being compared. Three passes will be required.
First Pass:
(51428) ( 1 5 4 2 8 ), Here, algorithm compares the first two elements, and swaps since 5 > 1.
(15428) ( 1 4 5 2 8 ), Swap since 5 > 4
(14528) ( 1 4 2 5 8 ), Swap since 5 > 2
(14258) ( 1 4 2 5 8 ), Now, since these elements are already in order (8 > 5), algorithm does not swap them.
Second Pass:
(14258) (14258)
(14258) ( 1 2 4 5 8 ), Swap since 4 > 2
(12458) (12458)
(12458) (12458)
Now, the array is already sorted, but our algorithm does not know if it is completed. The algorithm needs one whole pass
without any swap to know it is sorted.
http://en.wikipedia.org/wiki/Bubble_sort 2/6
2/26/2015 Bubble sort - Wikipedia, the free encyclopedia
Third Pass:
(12458) (12458)
(12458) (12458)
(12458) (12458)
(12458) (12458)
Implementation
Pseudocode implementation
The algorithm can be expressed as (0-based array):
More generally, it can happen that more than one element is placed in their final position on a single pass. In particular,
after every pass, all elements after the last swap are sorted, and do not need to be checked again. This allows us to skip
over a lot of the elements, resulting in about a worst case 50% improvement in comparison count (though no
improvement in swap counts), and adds very little complexity because the new code subsumes the "swapped" variable:
Alternate modifications, such as the cocktail shaker sort attempt to improve on the bubble sort performance while
keeping the same idea of repeatedly comparing and swapping adjacent items.
In practice
Although bubble sort is one of the simplest sorting algorithms to
understand and implement, its O(n2) complexity means that its
efficiency decreases dramatically on lists of more than a small number
of elements. Even among simple O(n2) sorting algorithms, algorithms
like insertion sort are usually considerably more efficient.
Due to its simplicity, bubble sort is often used to introduce the concept
of an algorithm, or a sorting algorithm, to introductory computer science
students. However, some researchers such as Owen Astrachan have gone
to great lengths to disparage bubble sort and its continued popularity in
computer science education, recommending that it no longer even be
taught.[2]
The Jargon File, which famously calls bogosort "the archetypical [sic] A bubble sort, a sorting algorithm that
perversely awful algorithm", also calls bubble sort "the generic bad continuously steps through a list, swapping
items until they appear in the correct order. The
algorithm".[3] Donald Knuth, in his famous book The Art of Computer list was plotted in a Cartesian coordinate
Programming, concluded that "the bubble sort seems to have nothing to
system, with each point (x,y) indicating that the
recommend it, except a catchy name and the fact that it leads to some value y is stored at index x. Then the list would
interesting theoretical problems", some of which he then discusses.[1] be sorted by Bubble sort according to every
pixel's value. Note that the largest end gets
Bubble sort is asymptotically equivalent in running time to insertion sort sorted first, with smaller elements taking longer
in the worst case, but the two algorithms differ greatly in the number of to move to their correct positions.
swaps necessary. Experimental results such as those of Astrachan have
also shown that insertion sort performs considerably better even on
random lists. For these reasons many modern algorithm textbooks avoid using the bubble sort algorithm in favor of
insertion sort.
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 one-fifth as fast an insertion sort and 70% as fast as a selection sort.[2]
In computer graphics it is popular for its capability to detect a very small error (like swap of just two elements) in almost-
sorted arrays and fix it with just linear complexity (2n). For example, it is used in a polygon filling algorithm, where
bounding lines are sorted by their x coordinate at a specific scan line (a line parallel to x axis) and with incrementing y
their order changes (two elements are swapped) only at intersections of two lines. Bubble sort is a stable sort algorithm,
like insertion sort.
Variations
Odd-even sort is a parallel version of bubble sort, for message passing systems.
http://en.wikipedia.org/wiki/Bubble_sort 4/6
2/26/2015 Bubble sort - Wikipedia, the free encyclopedia
For example, in Donald Knuth's The Art of Computer Programming, Volume 3: Sorting and Searching he states in
section 5.2.1 'Sorting by Insertion', that [the value] "settles to its proper level" this method of sorting has often been called
the sifting or sinking technique. Furthermore the larger values might be regarded as heavier and therefore be seen to
progressively sink to the bottom of the list.
Notes
1. ^ a b Donald Knuth. The Art of Computer Programming, Volume 3: Sorting and Searching, Second Edition. Addison-Wesley,
1998. ISBN 0-201-89685-0. Pages 106–110 of section 5.2.2: Sorting by Exchanging. "[A]lthough the techniques used in the
calculations [to analyze the bubble sort] are instructive, the results are disappointing since they tell us that the bubble sort isn't
really very good at all. Compared to straight insertion [...], bubble sorting requires a more complicated program and takes about
twice as long!" (Quote from the first edition, 1973.)
2. ^ a b Owen Astrachan. Bubble Sort: An Archaeological Algorithmic Analysis. SIGCSE 2003 Hannan Akhtar . (pdf)
(http://www.cs.duke.edu/~ola/papers/bubble.pdf)
3. ^ http://www.jargon.net/jargonfile/b/bogo-sort.html
4. ^ Black, Paul E. (24 August 2009). "bubble sort" (http://www.nist.gov/dads/HTML/bubblesort.html). Dictionary of Algorithms
and Data Structures. National Institute of Standards and Technology. Retrieved 1 October 2014.
References
Thomas H. Cormen, Charles E. Leiserson, Ronald L. Rivest, and Clifford Stein. Introduction to Algorithms,
Second Edition. MIT Press and McGraw-Hill, 2001. ISBN 0-262-03293-7. Problem 2-2, pg.40.
Sorting in the Presence of Branch Prediction and Caches (https://www.cs.tcd.ie/publications/tech-
reports/reports.05/TCD-CS-2005-57.pdf)
Fundamentals of Data Structures by Ellis Horowitz, Sartaj Sahni and Susan Anderson-Freed ISBN 81-7371-605-6
External links
David R. Martin. "Animated Sorting Algorithms: Bubble Sort" The Wikibook Algorithm
(http://www.sorting-algorithms.com/bubble-sort). – graphical implementation has a page
on the topic of: Bubble
demonstration and discussion of bubble sort sort
"Lafore's Bubble Sort" (http://lecture.ecc.u-
tokyo.ac.jp/~ueda/JavaApplet/BubbleSort.html). (Java applet animation) Wikimedia Commons has
media related to Bubble
(sequence A008302 in OEIS) Table (statistics) of the number of sort.
permutations of [n] that need k pair-swaps during the sorting.
Wikiversity has learning
materials about Bubble
Retrieved from "http://en.wikipedia.org/w/index.php? sort
http://en.wikipedia.org/wiki/Bubble_sort 5/6
2/26/2015 Bubble sort - Wikipedia, the free encyclopedia
title=Bubble_sort&oldid=648313032"
http://en.wikipedia.org/wiki/Bubble_sort 6/6