Edit count of the user (user_editcount ) | null |
Name of the user account (user_name ) | '72.33.2.12' |
Age of the user account (user_age ) | 0 |
Groups (including implicit) the user is in (user_groups ) | [
0 => '*'
] |
Rights that the user has (user_rights ) | [
0 => 'createaccount',
1 => 'read',
2 => 'edit',
3 => 'createtalk',
4 => 'writeapi',
5 => 'viewmyprivateinfo',
6 => 'editmyprivateinfo',
7 => 'editmyoptions',
8 => 'abusefilter-log-detail',
9 => 'urlshortener-create-url',
10 => 'centralauth-merge',
11 => 'abusefilter-view',
12 => 'abusefilter-log',
13 => 'vipsscaler-test'
] |
Whether or not a user is editing through the mobile interface (user_mobile ) | false |
Whether the user is editing from mobile app (user_app ) | false |
Page ID (page_id ) | 25977485 |
Page namespace (page_namespace ) | 0 |
Page title without namespace (page_title ) | 'Bubble sort' |
Full page title (page_prefixedtitle ) | 'Bubble sort' |
Edit protection level of the page (page_restrictions_edit ) | [] |
Last ten users to contribute to the page (page_recent_contributors ) | [
0 => '72.33.2.12',
1 => 'Bubba73',
2 => 'Skynxnex',
3 => '103.109.54.136',
4 => 'ClueBot NG',
5 => 'Philipnelson99',
6 => '2002:6736:DB48:B:BC4E:1FFB:B6F:F80D',
7 => '2002:6736:DB48:B:D086:8433:B37E:EFAC',
8 => '213.55.161.138',
9 => 'BD2412'
] |
Page age in seconds (page_age ) | 710558644 |
Action (action ) | 'edit' |
Edit summary/reason (summary ) | '' |
Time since last page edit in seconds (page_last_edit_age ) | 53 |
Old content model (old_content_model ) | 'wikitext' |
New content model (new_content_model ) | 'wikitext' |
Old page wikitext, before the edit (old_wikitext ) | '{{Short description|Simple comparison sorting algorithm}}
{{more citations needed|date=November 2016}}
{{Infobox Algorithm
|name={{PAGENAMEBASE}}|class=[[Sorting algorithm]]
|image=Bubblesort-edited-color.svg|
| caption=Static visualization of bubble sort<ref>{{cite web |last=Cortesi |first=Aldo |title=Visualising Sorting Algorithms |url=https://corte.si/posts/code/visualisingsorting/index.html |date=27 April 2007 |access-date=16 March 2017}}</ref>
|data=[[Array data structure|Array]]
|time=<math>O(n^2)</math> comparisons, <math>O(n^2)</math> swaps
|average-time=<math>O(n^2)</math> comparisons, <math>O(n^2)</math> swaps
|best-time=<math>O(n)</math> comparisons, <math>O(1)</math> swaps
|space=<math>O(n)</math> total, <math>O(1)</math> auxiliary
|optimal=No
}}
'''Binary Sort''', sometimes referred to as '''sinking sort''', is a simple [[sorting algorithm]] that repeatedly steps through the input list element by element, comparing the current element with the one after it, [[Swap (computer science)|swapping]] their values if needed. These passes through the list are repeated until no swaps have to be performed during a pass, meaning that the list has become fully sorted. The algorithm, which is a [[comparison sort]], is named for the way the larger elements "bubble" up to the top of the list.
This simple algorithm performs poorly in real world use and is used primarily as an educational tool. More efficient algorithms such as [[quicksort]], [[timsort]], or [[merge sort]] are used by the sorting libraries built into popular programming languages such as Python and Java.
However, if parallel processing is allowed, bubble sort sorts in O(n) time, making it considerably faster than parallel implementations of insertion sort or selection sort which do not parallelize as effectively.<ref>{{Cite web|url=https://bugs.openjdk.java.net/browse/JDK-6804124|title=[JDK-6804124] (coll) Replace "modified mergesort" in java.util.Arrays.sort with timsort - Java Bug System|website=bugs.openjdk.java.net|access-date=2020-01-11}}</ref><ref>{{Cite web|url=https://mail.python.org/pipermail/python-dev/2002-July/026837.html|title=[Python-Dev] Sorting|last=Peters|first=Tim|date=2002-07-20|access-date=2020-01-11}}</ref> <!-- sorted scan line display list stepped to next line is usually nearly sorted.
Bubble sort may be been found as early as 1956; then referred to as "sorting by exchange"<ref name="Astrachan">{{cite web |last1=Astrachan |first1=Owen |title=Bubble Sort: An Archaeological Algorithmic Analysis |url=https://users.cs.duke.edu/~ola/bubble/bubble.html |access-date=8 February 2019}}</ref> -->
==History==
The earliest description of the Bubble sort algorithm was in a 1956 paper by mathematician and actuary Edward Harry Friend,<ref>{{Cite web|url=https://www.legacy.com/us/obituaries/washingtonpost/name/edward-friend-obituary?id=1791684|title=EDWARD FRIEND Obituary (2019) - Washington, DC - The Washington Post|website=Legacy.com}}</ref> ''Sorting on electronic computer systems'',<ref>{{cite journal | doi=10.1145/320831.320833 | title=Sorting on Electronic Computer Systems | year=1956 | last1=Friend | first1=Edward H. | journal=Journal of the ACM | volume=3 | issue=3 | pages=134–168 | s2cid=16071355 | doi-access=free }}</ref> published in the third issue of the third volume of the ''[[Journal of the Association for Computing Machinery]]'' (ACM), as a "Sorting exchange algorithm". Friend described the fundamentals of the algorithm, and, although initially his paper went unnoticed, some years later, it was rediscovered by many computer scientists, including [[Kenneth E. Iverson]] who coined its current name.
==Analysis==
[[File:Bubble-sort-example-300px.gif|300px|thumb|right|An example of bubble sort. Starting from the beginning of the list, compare every adjacent pair, swap their position if they are not in the right order (the latter one is smaller than the former one). After each [[iteration]], one less element (the last one) is needed to be compared until there are no more elements left to be compared.]]
=== Performance ===
Bubble sort has a worst-case and average complexity of <math>O(n^2)</math>, where <math>n</math> is the number of items being sorted. Most practical sorting algorithms have substantially better worst-case or average complexity, often <math>O(n\log n)</math>. Even other <math>O(n^2)</math> sorting algorithms, such as [[insertion sort]], generally run faster than bubble sort, and are no more complex. For this reason, bubble sort is rarely used in practice.
Like [[insertion sort]], bubble sort is [[adaptive sort|adaptive]], which can give it an advantage over algorithms like [[quicksort]] . This means that it may outperform those algorithms in cases where the list is already mostly sorted (having a small number of [[inversion (discrete mathematics)|inversions]]), despite the fact that it has worse average-case time complexity. For example, bubble sort is <math>O(n)</math> on a list that is already sorted, while quicksort would still perform its entire <math>O(n \log n)</math> sorting process.
While any sorting algorithm can be made <math>O(n)</math> on a presorted list simply by checking the list before the algorithm runs, improved performance on almost-sorted lists is harder to replicate.
===Rabbits and turtles===
The distance and direction that elements must move during the sort determine bubble sort's performance because elements move in different directions at different speeds. An element that must move toward the end of the list can move quickly because it can take part in successive swaps. For example, the largest element in the list will win every swap, so it moves to its sorted position on the first pass even if it starts near the beginning. On the other hand, an element that must move toward the beginning of the list cannot move faster than one step per pass, so elements move toward the beginning very slowly. If the smallest element is at the end of the list, it will take <math>n -1</math> passes to move it to the beginning. This has led to these types of elements being named rabbits and turtles, respectively, after the characters in Aesop's fable of [[The Tortoise and the Hare]].
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 <math>O(n^2)</math> 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===
Take an 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
:( '''5''' '''1''' 4 2 8 ) → ( '''1''' '''5''' 4 2 8 ), Here, algorithm compares the first two elements, and swaps since 5 > 1.
:( 1 '''5''' '''4''' 2 8 ) → ( 1 '''4''' '''5''' 2 8 ), Swap since 5 > 4
:( 1 4 '''5''' '''2''' 8 ) → ( 1 4 '''2''' '''5''' 8 ), Swap since 5 > 2
:( 1 4 2 '''5''' '''8''' ) → ( 1 4 2 '''5''' '''8''' ), Now, since these elements are already in order (8 > 5), algorithm does not swap them.
;Second Pass
:( '''1''' '''4''' 2 5 8 ) → ( '''1''' '''4''' 2 5 8 )
:( 1 '''4''' '''2''' 5 8 ) → ( 1 '''2''' '''4''' 5 8 ), Swap since 4 > 2
:( 1 2 '''4''' '''5''' 8 ) → ( 1 2 '''4''' '''5''' 8 )
:( 1 2 4 '''5''' '''8''' ) → ( 1 2 4 '''5''' '''8''' )
Now, the array is already sorted, but the algorithm does not know if it is completed. The algorithm needs one additional '''whole''' pass without '''any''' swap to know it is sorted.
;Third Pass
:( '''1''' '''2''' 4 5 8 ) → ( '''1''' '''2''' 4 5 8 )
:( 1 '''2''' '''4''' 5 8 ) → ( 1 '''2''' '''4''' 5 8 )
:( 1 2 '''4''' '''5''' 8 ) → ( 1 2 '''4''' '''5''' 8 )
:( 1 2 4 '''5''' '''8''' ) → ( 1 2 4 '''5''' '''8''' )
== Implementation ==
=== Pseudocode implementation ===
In [[pseudocode]] the algorithm can be expressed as (0-based array):
<syntaxhighlight lang="pascal">
procedure bubbleSort(A : list of sortable items)
n := length(A)
repeat
swapped := false
for i := 1 to n-1 inclusive do
{ if this pair is out of order }
if A[i-1] > A[i] then
{ swap them and remember something changed }
swap(A[i-1], A[i])
swapped := true
end if
end for
until not swapped
end procedure
</syntaxhighlight>
=== Optimizing bubble sort ===
The bubble sort algorithm can be optimized by observing that the ''n''-th pass finds the ''n''-th largest element and puts it into its final place. So, the inner loop can avoid looking at the last ''n'' − 1 items when running for the ''n''-th time:
<syntaxhighlight lang="pascal">
procedure bubbleSort(A : list of sortable items)
n := length(A)
repeat
swapped := false
for i := 1 to n - 1 inclusive do
if A[i - 1] > A[i] then
swap(A[i - 1], A[i])
swapped := true
end if
end for
n := n - 1
until not swapped
end procedure
</syntaxhighlight>
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 many 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:
To accomplish this in pseudocode, the following can be written:
<syntaxhighlight lang="pascal">
procedure bubbleSort(A : list of sortable items)
n := length(A)
repeat
newn := 0
for i := 1 to n - 1 inclusive do
if A[i - 1] > A[i] then
swap(A[i - 1], A[i])
newn := i
end if
end for
n := newn
until n ≤ 1
end procedure
</syntaxhighlight>
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.
==Use==
[[File:Bubble sort animation.gif|thumb|right|280px|Bubble sort. The list was plotted in a Cartesian coordinate system, with each point (''x'', ''y'') indicating that the value ''y'' is stored at index ''x''. Then the list would be sorted by bubble sort according to every pixel's value. Note that the largest end gets sorted first, with smaller elements taking longer to move to their correct positions.]]
Although bubble sort is one of the simplest sorting algorithms to understand and implement, its [[Big O notation|''O''(''n''<sup>2</sup>)]] complexity means that its efficiency decreases dramatically on lists of more than a small number of elements. Even among simple ''O''(''n''<sup>2</sup>) 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.<ref name="Astrachan2003" />
The [[Jargon File]], which famously calls [[bogosort]] "the archetypical [sic] perversely awful algorithm", also calls bubble sort "the generic bad algorithm".<ref>{{Cite web|url=http://www.jargon.net/jargonfile/b/bogo-sort.html|title=jargon, node: bogo-sort|website=www.jargon.net}}</ref> [[Donald Knuth]], in ''[[The Art of Computer Programming]]'', concluded that "the bubble sort seems to have nothing to recommend it, except a catchy name and the fact that it leads to some interesting theoretical problems", some of which he then discusses.<ref name="Knuth">[[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.)</ref>
Bubble sort is [[Big O notation|asymptotically]] equivalent in running time to insertion sort in the worst case, but the two algorithms differ greatly in the number of 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 produces at least twice as many writes as insertion sort, twice as many cache misses, and asymptotically more [[Branch predictor|branch mispredictions]].{{citation needed|date=August 2015}} Experiments by Astrachan sorting strings in [[Java (programming language)|Java]] show bubble sort to be roughly one-fifth as fast as an insertion sort and 70% as fast as a [[selection sort]].<ref name="Astrachan2003">{{cite journal |last1=Astrachan |first1=Owen |title=Bubble sort: an archaeological algorithmic analysis |url=http://www.cs.duke.edu/~ola/papers/bubble.pdf |journal=ACM SIGCSE Bulletin |volume=35 |issue=1 |year=2003 |pages=1–5 |issn=0097-8418 |doi=10.1145/792548.611918}}</ref>
In computer graphics bubble sort 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 (2''n''). 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 the ''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.
* Passes can be from right to left, rather than left to right. This is more efficient for lists with unsorted items added to the end.
* [[Cocktail shaker sort]] alternates leftwards and rightwards passes.
== Debate over name ==
Bubble sort has been occasionally referred to as a "sinking sort".<ref>{{cite web |url=https://xlinux.nist.gov/dads/HTML/bubblesort.html |title=bubble sort |last=Black |first=Paul E. |date=24 August 2009 |work=[[Dictionary of Algorithms and Data Structures]] |publisher=[[National Institute of Standards and Technology]] |access-date=1 October 2014}}</ref>
For example, Donald Knuth describes the insertion of values at or towards their desired location as letting "[the value] settle to its proper level", and that "this method of sorting has sometimes been called the ''sifting'' or ''sinking'' technique.<ref>{{cite book|first1=Donald |last1=Knuth |author-link=Donald Knuth |title=The Art of Computer Programming: Volume 3: Searching and Sorting |year=1997 |page=80 |publisher=Addison-Wesley |isbn=0201896850}}</ref>
This debate is perpetuated by the ease with which one may consider this algorithm from two different but equally valid perspectives:
# The ''larger'' values might be regarded as ''heavier'' and therefore be seen to progressively ''sink'' to the ''bottom'' of the list
# The ''smaller'' values might be regarded as ''lighter'' and therefore be seen to progressively ''bubble up'' to the ''top'' of the list.
== In popular culture ==
In 2007, former [[Google]] CEO [[Eric Schmidt]] asked then-presidential candidate [[Barack Obama]] during an interview about the best way to sort one million [[integer]]s; Obama paused for a moment and replied: "I think the bubble sort would be the wrong way to go."<ref>{{Cite magazine|last=Lai Stirland|first=Sarah|date=2007-11-14|title=Obama Passes His Google Interview|url=https://www.wired.com/2007/11/obama-elect-me/|access-date=2020-10-27|magazine=Wired}}</ref><ref>{{cite AV media|url=https://www.youtube.com/watch?v=m4yVlPqeZwo|title=Barack Obama | Candidates at Google|date=Nov 14, 2007|people=Barack Obama, Eric Schmidt|language=en|publisher=Talks at Google|location=Mountain View, CA 94043 The Googleplex|time=23:20|access-date=Sep 18, 2019|archive-url=https://web.archive.org/web/20190907131624/https://www.youtube.com/watch?v=m4yVlPqeZwo|archive-date=September 7, 2019|url-status=live|format=Video|medium=YouTube}}</ref>
== Notes ==
<references />
== 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.
* [https://www.cs.tcd.ie/publications/tech-reports/reports.05/TCD-CS-2005-57.pdf Sorting in the Presence of Branch Prediction and Caches]
* Fundamentals of Data Structures by Ellis Horowitz, [[Sartaj Sahni]] and Susan Anderson-Freed {{ISBN|81-7371-605-6}}
* [[Owen Astrachan]]. [https://users.cs.duke.edu/~ola/bubble/bubble.html Bubble Sort: An Archaeological Algorithmic Analysis]
*Computer Integrated Manufacturing by Spasic PhD, Srdic MSc, [[Open Source, 1987]].[http://spms.masfak.ni.ac.rs/end/papers/55.%20177-HYBRID%20CONTROLLER%20FOR%20SYSTEM%20MANAGEMENT%20OF%20INTEGRATED%20UNIVERSITY.doc]
==External links==
{{wikibooks|Algorithm implementation|Sorting/Bubble_sort|Bubble sort}}
{{commons category|Bubble sort}}
{{wikiversity|Bubble sort}}
* {{cite web |last=Martin |first=David R. |url=http://www.sorting-algorithms.com/bubble-sort |archive-date=2015-03-03 |archive-url=https://web.archive.org/web/20150303084352/http://www.sorting-algorithms.com/bubble-sort |date=2007 |title=Animated Sorting Algorithms: Bubble Sort}} – graphical demonstration
* {{cite web | url= http://lecture.ecc.u-tokyo.ac.jp/~ueda/JavaApplet/BubbleSort.html |title= Lafore's Bubble Sort}} (Java applet animation)
* {{OEIS el|1=A008302|2=Table (statistics) of the number of permutations of <nowiki>[n]</nowiki> that need k pair-swaps during the sorting|formalname=Triangle of Mahonian numbers T(n,k): coefficients in expansion of Product_{i=0..n-1} (1 + x + ... + x^i), where k ranges from 0 to A000217(n-1)}}
{{sorting}}
[[Category:Articles with example pseudocode]]
[[Category:Comparison sorts]]
[[Category:Stable sorts]]
[[no:Sorteringsalgoritme#Boblesortering]]' |
New page wikitext, after the edit (new_wikitext ) | '{{Short description|Simple comparison sorting algorithm}}
{{more citations needed|date=November 2016}}
{{Infobox Algorithm
|name={{PAGENAMEBASE}}|class=[[Sorting algorithm]]
|image=Bubblesort-edited-color.svg|
| caption=Static visualization of bubble sort<ref>{{cite web |last=Cortesi |first=Aldo |title=Visualising Sorting Algorithms |url=https://corte.si/posts/code/visualisingsorting/index.html |date=27 April 2007 |access-date=16 March 2017}}</ref>
|data=[[Array data structure|Array]]
|time=<math>O(n^2)</math> comparisons, <math>O(n^2)</math> swaps
|average-time=<math>O(n^2)</math> comparisons, <math>O(n^2)</math> swaps
|best-time=<math>O(n)</math> comparisons, <math>O(1)</math> swaps
|space=<math>O(n)</math> total, <math>O(1)</math> auxiliary
|optimal=No
}}
'''Binary Sort''', sometimes referred to as '''sinking sort''', is a simple [[sorting algorithm]] that repeatedly steps through the input list element by element, comparing the current element with the one after it, [[Swap (computer science)|swapping]] their values if needed. These passes through the list are repeated until no swaps have to be performed during a pass, meaning that the list has become fully sorted. The algorithm, which is a [[comparison sort]], is named for the way the larger elements "bubble" up to the top of the list.
THERE IS NO BUBBLE SORT
=== Performance ===
Bubble sort has a worst-case and average complexity of <math>O(n^2)</math>, where <math>n</math> is the number of items being sorted. Most practical sorting algorithms have substantially better worst-case or average complexity, often <math>O(n\log n)</math>. Even other <math>O(n^2)</math> sorting algorithms, such as [[insertion sort]], generally run faster than bubble sort, and are no more complex. For this reason, bubble sort is rarely used in practice.
Like [[insertion sort]], bubble sort is [[adaptive sort|adaptive]], which can give it an advantage over algorithms like [[quicksort]] . This means that it may outperform those algorithms in cases where the list is already mostly sorted (having a small number of [[inversion (discrete mathematics)|inversions]]), despite the fact that it has worse average-case time complexity. For example, bubble sort is <math>O(n)</math> on a list that is already sorted, while quicksort would still perform its entire <math>O(n \log n)</math> sorting process.
While any sorting algorithm can be made <math>O(n)</math> on a presorted list simply by checking the list before the algorithm runs, improved performance on almost-sorted lists is harder to replicate.
===Rabbits and turtles===
The distance and direction that elements must move during the sort determine bubble sort's performance because elements move in different directions at different speeds. An element that must move toward the end of the list can move quickly because it can take part in successive swaps. For example, the largest element in the list will win every swap, so it moves to its sorted position on the first pass even if it starts near the beginning. On the other hand, an element that must move toward the beginning of the list cannot move faster than one step per pass, so elements move toward the beginning very slowly. If the smallest element is at the end of the list, it will take <math>n -1</math> passes to move it to the beginning. This has led to these types of elements being named rabbits and turtles, respectively, after the characters in Aesop's fable of [[The Tortoise and the Hare]].
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 <math>O(n^2)</math> 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===
Take an 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
:( '''5''' '''1''' 4 2 8 ) → ( '''1''' '''5''' 4 2 8 ), Here, algorithm compares the first two elements, and swaps since 5 > 1.
:( 1 '''5''' '''4''' 2 8 ) → ( 1 '''4''' '''5''' 2 8 ), Swap since 5 > 4
:( 1 4 '''5''' '''2''' 8 ) → ( 1 4 '''2''' '''5''' 8 ), Swap since 5 > 2
:( 1 4 2 '''5''' '''8''' ) → ( 1 4 2 '''5''' '''8''' ), Now, since these elements are already in order (8 > 5), algorithm does not swap them.
;Second Pass
:( '''1''' '''4''' 2 5 8 ) → ( '''1''' '''4''' 2 5 8 )
:( 1 '''4''' '''2''' 5 8 ) → ( 1 '''2''' '''4''' 5 8 ), Swap since 4 > 2
:( 1 2 '''4''' '''5''' 8 ) → ( 1 2 '''4''' '''5''' 8 )
:( 1 2 4 '''5''' '''8''' ) → ( 1 2 4 '''5''' '''8''' )
Now, the array is already sorted, but the algorithm does not know if it is completed. The algorithm needs one additional '''whole''' pass without '''any''' swap to know it is sorted.
;Third Pass
:( '''1''' '''2''' 4 5 8 ) → ( '''1''' '''2''' 4 5 8 )
:( 1 '''2''' '''4''' 5 8 ) → ( 1 '''2''' '''4''' 5 8 )
:( 1 2 '''4''' '''5''' 8 ) → ( 1 2 '''4''' '''5''' 8 )
:( 1 2 4 '''5''' '''8''' ) → ( 1 2 4 '''5''' '''8''' )
== Implementation ==
=== Pseudocode implementation ===
In [[pseudocode]] the algorithm can be expressed as (0-based array):
<syntaxhighlight lang="pascal">
procedure bubbleSort(A : list of sortable items)
n := length(A)
repeat
swapped := false
for i := 1 to n-1 inclusive do
{ if this pair is out of order }
if A[i-1] > A[i] then
{ swap them and remember something changed }
swap(A[i-1], A[i])
swapped := true
end if
end for
until not swapped
end procedure
</syntaxhighlight>
=== Optimizing bubble sort ===
The bubble sort algorithm can be optimized by observing that the ''n''-th pass finds the ''n''-th largest element and puts it into its final place. So, the inner loop can avoid looking at the last ''n'' − 1 items when running for the ''n''-th time:
<syntaxhighlight lang="pascal">
procedure bubbleSort(A : list of sortable items)
n := length(A)
repeat
swapped := false
for i := 1 to n - 1 inclusive do
if A[i - 1] > A[i] then
swap(A[i - 1], A[i])
swapped := true
end if
end for
n := n - 1
until not swapped
end procedure
</syntaxhighlight>
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 many 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:
To accomplish this in pseudocode, the following can be written:
<syntaxhighlight lang="pascal">
procedure bubbleSort(A : list of sortable items)
n := length(A)
repeat
newn := 0
for i := 1 to n - 1 inclusive do
if A[i - 1] > A[i] then
swap(A[i - 1], A[i])
newn := i
end if
end for
n := newn
until n ≤ 1
end procedure
</syntaxhighlight>
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.
==Use==
[[File:Bubble sort animation.gif|thumb|right|280px|Bubble sort. The list was plotted in a Cartesian coordinate system, with each point (''x'', ''y'') indicating that the value ''y'' is stored at index ''x''. Then the list would be sorted by bubble sort according to every pixel's value. Note that the largest end gets sorted first, with smaller elements taking longer to move to their correct positions.]]
Although bubble sort is one of the simplest sorting algorithms to understand and implement, its [[Big O notation|''O''(''n''<sup>2</sup>)]] complexity means that its efficiency decreases dramatically on lists of more than a small number of elements. Even among simple ''O''(''n''<sup>2</sup>) 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.<ref name="Astrachan2003" />
The [[Jargon File]], which famously calls [[bogosort]] "the archetypical [sic] perversely awful algorithm", also calls bubble sort "the generic bad algorithm".<ref>{{Cite web|url=http://www.jargon.net/jargonfile/b/bogo-sort.html|title=jargon, node: bogo-sort|website=www.jargon.net}}</ref> [[Donald Knuth]], in ''[[The Art of Computer Programming]]'', concluded that "the bubble sort seems to have nothing to recommend it, except a catchy name and the fact that it leads to some interesting theoretical problems", some of which he then discusses.<ref name="Knuth">[[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.)</ref>
Bubble sort is [[Big O notation|asymptotically]] equivalent in running time to insertion sort in the worst case, but the two algorithms differ greatly in the number of 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 produces at least twice as many writes as insertion sort, twice as many cache misses, and asymptotically more [[Branch predictor|branch mispredictions]].{{citation needed|date=August 2015}} Experiments by Astrachan sorting strings in [[Java (programming language)|Java]] show bubble sort to be roughly one-fifth as fast as an insertion sort and 70% as fast as a [[selection sort]].<ref name="Astrachan2003">{{cite journal |last1=Astrachan |first1=Owen |title=Bubble sort: an archaeological algorithmic analysis |url=http://www.cs.duke.edu/~ola/papers/bubble.pdf |journal=ACM SIGCSE Bulletin |volume=35 |issue=1 |year=2003 |pages=1–5 |issn=0097-8418 |doi=10.1145/792548.611918}}</ref>
In computer graphics bubble sort 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 (2''n''). 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 the ''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.
* Passes can be from right to left, rather than left to right. This is more efficient for lists with unsorted items added to the end.
* [[Cocktail shaker sort]] alternates leftwards and rightwards passes.
== Debate over name ==
Bubble sort has been occasionally referred to as a "sinking sort".<ref>{{cite web |url=https://xlinux.nist.gov/dads/HTML/bubblesort.html |title=bubble sort |last=Black |first=Paul E. |date=24 August 2009 |work=[[Dictionary of Algorithms and Data Structures]] |publisher=[[National Institute of Standards and Technology]] |access-date=1 October 2014}}</ref>
For example, Donald Knuth describes the insertion of values at or towards their desired location as letting "[the value] settle to its proper level", and that "this method of sorting has sometimes been called the ''sifting'' or ''sinking'' technique.<ref>{{cite book|first1=Donald |last1=Knuth |author-link=Donald Knuth |title=The Art of Computer Programming: Volume 3: Searching and Sorting |year=1997 |page=80 |publisher=Addison-Wesley |isbn=0201896850}}</ref>
This debate is perpetuated by the ease with which one may consider this algorithm from two different but equally valid perspectives:
# The ''larger'' values might be regarded as ''heavier'' and therefore be seen to progressively ''sink'' to the ''bottom'' of the list
# The ''smaller'' values might be regarded as ''lighter'' and therefore be seen to progressively ''bubble up'' to the ''top'' of the list.
== In popular culture ==
In 2007, former [[Google]] CEO [[Eric Schmidt]] asked then-presidential candidate [[Barack Obama]] during an interview about the best way to sort one million [[integer]]s; Obama paused for a moment and replied: "I think the bubble sort would be the wrong way to go."<ref>{{Cite magazine|last=Lai Stirland|first=Sarah|date=2007-11-14|title=Obama Passes His Google Interview|url=https://www.wired.com/2007/11/obama-elect-me/|access-date=2020-10-27|magazine=Wired}}</ref><ref>{{cite AV media|url=https://www.youtube.com/watch?v=m4yVlPqeZwo|title=Barack Obama | Candidates at Google|date=Nov 14, 2007|people=Barack Obama, Eric Schmidt|language=en|publisher=Talks at Google|location=Mountain View, CA 94043 The Googleplex|time=23:20|access-date=Sep 18, 2019|archive-url=https://web.archive.org/web/20190907131624/https://www.youtube.com/watch?v=m4yVlPqeZwo|archive-date=September 7, 2019|url-status=live|format=Video|medium=YouTube}}</ref>
== Notes ==
<references />
== 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.
* [https://www.cs.tcd.ie/publications/tech-reports/reports.05/TCD-CS-2005-57.pdf Sorting in the Presence of Branch Prediction and Caches]
* Fundamentals of Data Structures by Ellis Horowitz, [[Sartaj Sahni]] and Susan Anderson-Freed {{ISBN|81-7371-605-6}}
* [[Owen Astrachan]]. [https://users.cs.duke.edu/~ola/bubble/bubble.html Bubble Sort: An Archaeological Algorithmic Analysis]
*Computer Integrated Manufacturing by Spasic PhD, Srdic MSc, [[Open Source, 1987]].[http://spms.masfak.ni.ac.rs/end/papers/55.%20177-HYBRID%20CONTROLLER%20FOR%20SYSTEM%20MANAGEMENT%20OF%20INTEGRATED%20UNIVERSITY.doc]
==External links==
{{wikibooks|Algorithm implementation|Sorting/Bubble_sort|Bubble sort}}
{{commons category|Bubble sort}}
{{wikiversity|Bubble sort}}
* {{cite web |last=Martin |first=David R. |url=http://www.sorting-algorithms.com/bubble-sort |archive-date=2015-03-03 |archive-url=https://web.archive.org/web/20150303084352/http://www.sorting-algorithms.com/bubble-sort |date=2007 |title=Animated Sorting Algorithms: Bubble Sort}} – graphical demonstration
* {{cite web | url= http://lecture.ecc.u-tokyo.ac.jp/~ueda/JavaApplet/BubbleSort.html |title= Lafore's Bubble Sort}} (Java applet animation)
* {{OEIS el|1=A008302|2=Table (statistics) of the number of permutations of <nowiki>[n]</nowiki> that need k pair-swaps during the sorting|formalname=Triangle of Mahonian numbers T(n,k): coefficients in expansion of Product_{i=0..n-1} (1 + x + ... + x^i), where k ranges from 0 to A000217(n-1)}}
{{sorting}}
[[Category:Articles with example pseudocode]]
[[Category:Comparison sorts]]
[[Category:Stable sorts]]
[[no:Sorteringsalgoritme#Boblesortering]]' |
Unified diff of changes made by edit (edit_diff ) | '@@ -14,14 +14,5 @@
'''Binary Sort''', sometimes referred to as '''sinking sort''', is a simple [[sorting algorithm]] that repeatedly steps through the input list element by element, comparing the current element with the one after it, [[Swap (computer science)|swapping]] their values if needed. These passes through the list are repeated until no swaps have to be performed during a pass, meaning that the list has become fully sorted. The algorithm, which is a [[comparison sort]], is named for the way the larger elements "bubble" up to the top of the list.
-This simple algorithm performs poorly in real world use and is used primarily as an educational tool. More efficient algorithms such as [[quicksort]], [[timsort]], or [[merge sort]] are used by the sorting libraries built into popular programming languages such as Python and Java.
-However, if parallel processing is allowed, bubble sort sorts in O(n) time, making it considerably faster than parallel implementations of insertion sort or selection sort which do not parallelize as effectively.<ref>{{Cite web|url=https://bugs.openjdk.java.net/browse/JDK-6804124|title=[JDK-6804124] (coll) Replace "modified mergesort" in java.util.Arrays.sort with timsort - Java Bug System|website=bugs.openjdk.java.net|access-date=2020-01-11}}</ref><ref>{{Cite web|url=https://mail.python.org/pipermail/python-dev/2002-July/026837.html|title=[Python-Dev] Sorting|last=Peters|first=Tim|date=2002-07-20|access-date=2020-01-11}}</ref> <!-- sorted scan line display list stepped to next line is usually nearly sorted.
-
-Bubble sort may be been found as early as 1956; then referred to as "sorting by exchange"<ref name="Astrachan">{{cite web |last1=Astrachan |first1=Owen |title=Bubble Sort: An Archaeological Algorithmic Analysis |url=https://users.cs.duke.edu/~ola/bubble/bubble.html |access-date=8 February 2019}}</ref> -->
-
-==History==
-The earliest description of the Bubble sort algorithm was in a 1956 paper by mathematician and actuary Edward Harry Friend,<ref>{{Cite web|url=https://www.legacy.com/us/obituaries/washingtonpost/name/edward-friend-obituary?id=1791684|title=EDWARD FRIEND Obituary (2019) - Washington, DC - The Washington Post|website=Legacy.com}}</ref> ''Sorting on electronic computer systems'',<ref>{{cite journal | doi=10.1145/320831.320833 | title=Sorting on Electronic Computer Systems | year=1956 | last1=Friend | first1=Edward H. | journal=Journal of the ACM | volume=3 | issue=3 | pages=134–168 | s2cid=16071355 | doi-access=free }}</ref> published in the third issue of the third volume of the ''[[Journal of the Association for Computing Machinery]]'' (ACM), as a "Sorting exchange algorithm". Friend described the fundamentals of the algorithm, and, although initially his paper went unnoticed, some years later, it was rediscovered by many computer scientists, including [[Kenneth E. Iverson]] who coined its current name.
-
-==Analysis==
-[[File:Bubble-sort-example-300px.gif|300px|thumb|right|An example of bubble sort. Starting from the beginning of the list, compare every adjacent pair, swap their position if they are not in the right order (the latter one is smaller than the former one). After each [[iteration]], one less element (the last one) is needed to be compared until there are no more elements left to be compared.]]
+THERE IS NO BUBBLE SORT
=== Performance ===
' |
New page size (new_size ) | 16346 |
Old page size (old_size ) | 19073 |
Size change in edit (edit_delta ) | -2727 |
Lines added in edit (added_lines ) | [
0 => 'THERE IS NO BUBBLE SORT'
] |
Lines removed in edit (removed_lines ) | [
0 => 'This simple algorithm performs poorly in real world use and is used primarily as an educational tool. More efficient algorithms such as [[quicksort]], [[timsort]], or [[merge sort]] are used by the sorting libraries built into popular programming languages such as Python and Java. ',
1 => 'However, if parallel processing is allowed, bubble sort sorts in O(n) time, making it considerably faster than parallel implementations of insertion sort or selection sort which do not parallelize as effectively.<ref>{{Cite web|url=https://bugs.openjdk.java.net/browse/JDK-6804124|title=[JDK-6804124] (coll) Replace "modified mergesort" in java.util.Arrays.sort with timsort - Java Bug System|website=bugs.openjdk.java.net|access-date=2020-01-11}}</ref><ref>{{Cite web|url=https://mail.python.org/pipermail/python-dev/2002-July/026837.html|title=[Python-Dev] Sorting|last=Peters|first=Tim|date=2002-07-20|access-date=2020-01-11}}</ref> <!-- sorted scan line display list stepped to next line is usually nearly sorted.',
2 => '',
3 => 'Bubble sort may be been found as early as 1956; then referred to as "sorting by exchange"<ref name="Astrachan">{{cite web |last1=Astrachan |first1=Owen |title=Bubble Sort: An Archaeological Algorithmic Analysis |url=https://users.cs.duke.edu/~ola/bubble/bubble.html |access-date=8 February 2019}}</ref> -->',
4 => '',
5 => '==History==',
6 => 'The earliest description of the Bubble sort algorithm was in a 1956 paper by mathematician and actuary Edward Harry Friend,<ref>{{Cite web|url=https://www.legacy.com/us/obituaries/washingtonpost/name/edward-friend-obituary?id=1791684|title=EDWARD FRIEND Obituary (2019) - Washington, DC - The Washington Post|website=Legacy.com}}</ref> ''Sorting on electronic computer systems'',<ref>{{cite journal | doi=10.1145/320831.320833 | title=Sorting on Electronic Computer Systems | year=1956 | last1=Friend | first1=Edward H. | journal=Journal of the ACM | volume=3 | issue=3 | pages=134–168 | s2cid=16071355 | doi-access=free }}</ref> published in the third issue of the third volume of the ''[[Journal of the Association for Computing Machinery]]'' (ACM), as a "Sorting exchange algorithm". Friend described the fundamentals of the algorithm, and, although initially his paper went unnoticed, some years later, it was rediscovered by many computer scientists, including [[Kenneth E. Iverson]] who coined its current name.',
7 => '',
8 => '==Analysis==',
9 => '[[File:Bubble-sort-example-300px.gif|300px|thumb|right|An example of bubble sort. Starting from the beginning of the list, compare every adjacent pair, swap their position if they are not in the right order (the latter one is smaller than the former one). After each [[iteration]], one less element (the last one) is needed to be compared until there are no more elements left to be compared.]]'
] |
All external links added in the edit (added_links ) | [] |
All external links removed in the edit (removed_links ) | [
0 => 'https://bugs.openjdk.java.net/browse/JDK-6804124',
1 => 'https://mail.python.org/pipermail/python-dev/2002-July/026837.html',
2 => 'https://www.legacy.com/us/obituaries/washingtonpost/name/edward-friend-obituary?id=1791684',
3 => 'https://doi.org/10.1145%2F320831.320833',
4 => 'https://api.semanticscholar.org/CorpusID:16071355'
] |
All external links in the new text (all_links ) | [
0 => 'https://corte.si/posts/code/visualisingsorting/index.html',
1 => 'http://www.cs.duke.edu/~ola/papers/bubble.pdf',
2 => 'https://doi.org/10.1145%2F792548.611918',
3 => 'https://www.worldcat.org/issn/0097-8418',
4 => 'http://www.jargon.net/jargonfile/b/bogo-sort.html',
5 => 'https://xlinux.nist.gov/dads/HTML/bubblesort.html',
6 => 'https://www.wired.com/2007/11/obama-elect-me/',
7 => 'https://www.youtube.com/watch?v=m4yVlPqeZwo',
8 => 'https://web.archive.org/web/20190907131624/https://www.youtube.com/watch?v=m4yVlPqeZwo',
9 => 'https://www.google.com/search?as_eq=wikipedia&q=%22Bubble+sort%22',
10 => 'https://www.google.com/search?tbm=nws&q=%22Bubble+sort%22+-wikipedia&tbs=ar:1',
11 => 'https://www.google.com/search?&q=%22Bubble+sort%22&tbs=bkt:s&tbm=bks',
12 => 'https://www.google.com/search?tbs=bks:1&q=%22Bubble+sort%22+-wikipedia',
13 => 'https://scholar.google.com/scholar?q=%22Bubble+sort%22',
14 => 'https://www.jstor.org/action/doBasicSearch?Query=%22Bubble+sort%22&acc=on&wc=on',
15 => 'https://www.cs.tcd.ie/publications/tech-reports/reports.05/TCD-CS-2005-57.pdf',
16 => 'https://users.cs.duke.edu/~ola/bubble/bubble.html',
17 => 'http://spms.masfak.ni.ac.rs/end/papers/55.%20177-HYBRID%20CONTROLLER%20FOR%20SYSTEM%20MANAGEMENT%20OF%20INTEGRATED%20UNIVERSITY.doc',
18 => 'https://web.archive.org/web/20150303084352/http://www.sorting-algorithms.com/bubble-sort',
19 => 'http://www.sorting-algorithms.com/bubble-sort',
20 => 'http://lecture.ecc.u-tokyo.ac.jp/~ueda/JavaApplet/BubbleSort.html',
21 => 'https://oeis.org/A008302'
] |
Links in the page, before the edit (old_links ) | [
0 => 'https://corte.si/posts/code/visualisingsorting/index.html',
1 => 'http://www.cs.duke.edu/~ola/papers/bubble.pdf',
2 => 'http://www.jargon.net/jargonfile/b/bogo-sort.html',
3 => 'https://xlinux.nist.gov/dads/HTML/bubblesort.html',
4 => 'https://www.cs.tcd.ie/publications/tech-reports/reports.05/TCD-CS-2005-57.pdf',
5 => 'https://web.archive.org/web/20150303084352/http://www.sorting-algorithms.com/bubble-sort',
6 => 'http://www.sorting-algorithms.com/bubble-sort',
7 => 'http://lecture.ecc.u-tokyo.ac.jp/~ueda/JavaApplet/BubbleSort.html',
8 => 'https://oeis.org/A008302',
9 => 'https://users.cs.duke.edu/~ola/bubble/bubble.html',
10 => 'https://www.wired.com/2007/11/obama-elect-me/',
11 => 'https://web.archive.org/web/20190907131624/https://www.youtube.com/watch?v=m4yVlPqeZwo',
12 => 'https://www.youtube.com/watch?v=m4yVlPqeZwo',
13 => 'https://bugs.openjdk.java.net/browse/JDK-6804124',
14 => 'https://mail.python.org/pipermail/python-dev/2002-July/026837.html',
15 => 'https://www.jstor.org/action/doBasicSearch?Query=%22Bubble+sort%22&acc=on&wc=on',
16 => 'http://spms.masfak.ni.ac.rs/end/papers/55.%20177-HYBRID%20CONTROLLER%20FOR%20SYSTEM%20MANAGEMENT%20OF%20INTEGRATED%20UNIVERSITY.doc',
17 => 'https://doi.org/10.1145%2F792548.611918',
18 => 'https://www.worldcat.org/issn/0097-8418',
19 => 'https://www.legacy.com/us/obituaries/washingtonpost/name/edward-friend-obituary?id=1791684',
20 => 'https://doi.org/10.1145%2F320831.320833',
21 => 'https://api.semanticscholar.org/CorpusID:16071355',
22 => 'https://www.google.com/search?as_eq=wikipedia&q=%22Bubble+sort%22',
23 => 'https://www.google.com/search?tbm=nws&q=%22Bubble+sort%22+-wikipedia&tbs=ar:1',
24 => 'https://www.google.com/search?&q=%22Bubble+sort%22&tbs=bkt:s&tbm=bks',
25 => 'https://www.google.com/search?tbs=bks:1&q=%22Bubble+sort%22+-wikipedia',
26 => 'https://scholar.google.com/scholar?q=%22Bubble+sort%22'
] |
Parsed HTML source of the new revision (new_html ) | '<div class="mw-content-ltr mw-parser-output" lang="en" dir="ltr"><div class="shortdescription nomobile noexcerpt noprint searchaux" style="display:none">Simple comparison sorting algorithm</div>
<style data-mw-deduplicate="TemplateStyles:r1097763485">.mw-parser-output .ambox{border:1px solid #a2a9b1;border-left:10px solid #36c;background-color:#fbfbfb;box-sizing:border-box}.mw-parser-output .ambox+link+.ambox,.mw-parser-output .ambox+link+style+.ambox,.mw-parser-output .ambox+link+link+.ambox,.mw-parser-output .ambox+.mw-empty-elt+link+.ambox,.mw-parser-output .ambox+.mw-empty-elt+link+style+.ambox,.mw-parser-output .ambox+.mw-empty-elt+link+link+.ambox{margin-top:-1px}html body.mediawiki .mw-parser-output .ambox.mbox-small-left{margin:4px 1em 4px 0;overflow:hidden;width:238px;border-collapse:collapse;font-size:88%;line-height:1.25em}.mw-parser-output .ambox-speedy{border-left:10px solid #b32424;background-color:#fee7e6}.mw-parser-output .ambox-delete{border-left:10px solid #b32424}.mw-parser-output .ambox-content{border-left:10px solid #f28500}.mw-parser-output .ambox-style{border-left:10px solid #fc3}.mw-parser-output .ambox-move{border-left:10px solid #9932cc}.mw-parser-output .ambox-protection{border-left:10px solid #a2a9b1}.mw-parser-output .ambox .mbox-text{border:none;padding:0.25em 0.5em;width:100%}.mw-parser-output .ambox .mbox-image{border:none;padding:2px 0 2px 0.5em;text-align:center}.mw-parser-output .ambox .mbox-imageright{border:none;padding:2px 0.5em 2px 0;text-align:center}.mw-parser-output .ambox .mbox-empty-cell{border:none;padding:0;width:1px}.mw-parser-output .ambox .mbox-image-div{width:52px}html.client-js body.skin-minerva .mw-parser-output .mbox-text-span{margin-left:23px!important}@media(min-width:720px){.mw-parser-output .ambox{margin:0 10%}}</style><table class="box-More_citations_needed plainlinks metadata ambox ambox-content ambox-Refimprove" role="presentation"><tbody><tr><td class="mbox-image"><div class="mbox-image-div"><span typeof="mw:File"><a href="/enwiki/wiki/File:Question_book-new.svg" class="mw-file-description"><img alt="" src="/upwiki/wikipedia/en/thumb/9/99/Question_book-new.svg/50px-Question_book-new.svg.png" decoding="async" width="50" height="39" class="mw-file-element" srcset="/upwiki/wikipedia/en/thumb/9/99/Question_book-new.svg/75px-Question_book-new.svg.png 1.5x, /upwiki/wikipedia/en/thumb/9/99/Question_book-new.svg/100px-Question_book-new.svg.png 2x" data-file-width="512" data-file-height="399" /></a></span></div></td><td class="mbox-text"><div class="mbox-text-span">This article <b>needs additional citations for <a href="/enwiki/wiki/Wikipedia:Verifiability" title="Wikipedia:Verifiability">verification</a></b>.<span class="hide-when-compact"> Please help <a href="/enwiki/wiki/Special:EditPage/Bubble_sort" title="Special:EditPage/Bubble sort">improve this article</a> by <a href="/enwiki/wiki/Help:Referencing_for_beginners" title="Help:Referencing for beginners">adding citations to reliable sources</a>. Unsourced material may be challenged and removed.<br /><small><span class="plainlinks"><i>Find sources:</i> <a rel="nofollow" class="external text" href="https://www.google.com/search?as_eq=wikipedia&q=%22Bubble+sort%22">"Bubble sort"</a> – <a rel="nofollow" class="external text" href="https://www.google.com/search?tbm=nws&q=%22Bubble+sort%22+-wikipedia&tbs=ar:1">news</a> <b>·</b> <a rel="nofollow" class="external text" href="https://www.google.com/search?&q=%22Bubble+sort%22&tbs=bkt:s&tbm=bks">newspapers</a> <b>·</b> <a rel="nofollow" class="external text" href="https://www.google.com/search?tbs=bks:1&q=%22Bubble+sort%22+-wikipedia">books</a> <b>·</b> <a rel="nofollow" class="external text" href="https://scholar.google.com/scholar?q=%22Bubble+sort%22">scholar</a> <b>·</b> <a rel="nofollow" class="external text" href="https://www.jstor.org/action/doBasicSearch?Query=%22Bubble+sort%22&acc=on&wc=on">JSTOR</a></span></small></span> <span class="date-container"><i>(<span class="date">November 2016</span>)</i></span><span class="hide-when-compact"><i> (<small><a href="/enwiki/wiki/Help:Maintenance_template_removal" title="Help:Maintenance template removal">Learn how and when to remove this message</a></small>)</i></span></div></td></tr></tbody></table>
<style data-mw-deduplicate="TemplateStyles:r1218072481">.mw-parser-output .infobox-subbox{padding:0;border:none;margin:-3px;width:auto;min-width:100%;font-size:100%;clear:none;float:none;background-color:transparent}.mw-parser-output .infobox-3cols-child{margin:auto}.mw-parser-output .infobox .navbar{font-size:100%}body.skin-minerva .mw-parser-output .infobox-header,body.skin-minerva .mw-parser-output .infobox-subheader,body.skin-minerva .mw-parser-output .infobox-above,body.skin-minerva .mw-parser-output .infobox-title,body.skin-minerva .mw-parser-output .infobox-image,body.skin-minerva .mw-parser-output .infobox-full-data,body.skin-minerva .mw-parser-output .infobox-below{text-align:center}html.skin-theme-clientpref-night .mw-parser-output .infobox-full-data div{background:#1f1f23!important;color:#f8f9fa}@media(prefers-color-scheme:dark){html.skin-theme-clientpref-os .mw-parser-output .infobox-full-data div{background:#1f1f23!important;color:#f8f9fa}}</style><table class="infobox"><caption class="infobox-title">Bubble sort</caption><tbody><tr><td colspan="2" class="infobox-image"><span class="mw-default-size" typeof="mw:File/Frameless"><a href="/enwiki/wiki/File:Bubblesort-edited-color.svg" class="mw-file-description"><img src="/upwiki/wikipedia/commons/thumb/8/83/Bubblesort-edited-color.svg/220px-Bubblesort-edited-color.svg.png" decoding="async" width="220" height="183" class="mw-file-element" srcset="/upwiki/wikipedia/commons/thumb/8/83/Bubblesort-edited-color.svg/330px-Bubblesort-edited-color.svg.png 1.5x, /upwiki/wikipedia/commons/thumb/8/83/Bubblesort-edited-color.svg/440px-Bubblesort-edited-color.svg.png 2x" data-file-width="512" data-file-height="427" /></a></span><div class="infobox-caption">Static visualization of bubble sort<sup id="cite_ref-1" class="reference"><a href="#cite_note-1">[1]</a></sup></div></td></tr><tr><th scope="row" class="infobox-label">Class</th><td class="infobox-data"><a href="/enwiki/wiki/Sorting_algorithm" title="Sorting algorithm">Sorting algorithm</a></td></tr><tr><th scope="row" class="infobox-label">Data structure</th><td class="infobox-data"><a href="/enwiki/wiki/Array_data_structure" class="mw-redirect" title="Array data structure">Array</a></td></tr><tr><th scope="row" class="infobox-label"><a href="/enwiki/wiki/Best,_worst_and_average_case" title="Best, worst and average case">Worst-case</a> <a href="/enwiki/wiki/Time_complexity" title="Time complexity">performance</a></th><td class="infobox-data"><span class="mwe-math-element"><span class="mwe-math-mathml-inline mwe-math-mathml-a11y" style="display: none;"><math xmlns="http://www.w3.org/1998/Math/MathML" alttext="{\displaystyle O(n^{2})}">
<semantics>
<mrow class="MJX-TeXAtom-ORD">
<mstyle displaystyle="true" scriptlevel="0">
<mi>O</mi>
<mo stretchy="false">(</mo>
<msup>
<mi>n</mi>
<mrow class="MJX-TeXAtom-ORD">
<mn>2</mn>
</mrow>
</msup>
<mo stretchy="false">)</mo>
</mstyle>
</mrow>
<annotation encoding="application/x-tex">{\displaystyle O(n^{2})}</annotation>
</semantics>
</math></span><img src="https://wikimedia.org/enwiki/api/rest_v1/media/math/render/svg/6cd9594a16cb898b8f2a2dff9227a385ec183392" class="mwe-math-fallback-image-inline mw-invert" aria-hidden="true" style="vertical-align: -0.838ex; width:6.032ex; height:3.176ex;" alt="{\displaystyle O(n^{2})}"></span> comparisons, <span class="mwe-math-element"><span class="mwe-math-mathml-inline mwe-math-mathml-a11y" style="display: none;"><math xmlns="http://www.w3.org/1998/Math/MathML" alttext="{\displaystyle O(n^{2})}">
<semantics>
<mrow class="MJX-TeXAtom-ORD">
<mstyle displaystyle="true" scriptlevel="0">
<mi>O</mi>
<mo stretchy="false">(</mo>
<msup>
<mi>n</mi>
<mrow class="MJX-TeXAtom-ORD">
<mn>2</mn>
</mrow>
</msup>
<mo stretchy="false">)</mo>
</mstyle>
</mrow>
<annotation encoding="application/x-tex">{\displaystyle O(n^{2})}</annotation>
</semantics>
</math></span><img src="https://wikimedia.org/enwiki/api/rest_v1/media/math/render/svg/6cd9594a16cb898b8f2a2dff9227a385ec183392" class="mwe-math-fallback-image-inline mw-invert" aria-hidden="true" style="vertical-align: -0.838ex; width:6.032ex; height:3.176ex;" alt="{\displaystyle O(n^{2})}"></span> swaps</td></tr><tr><th scope="row" class="infobox-label"><a href="/enwiki/wiki/Best,_worst_and_average_case" title="Best, worst and average case">Best-case</a> <a href="/enwiki/wiki/Time_complexity" title="Time complexity">performance</a></th><td class="infobox-data"><span class="mwe-math-element"><span class="mwe-math-mathml-inline mwe-math-mathml-a11y" style="display: none;"><math xmlns="http://www.w3.org/1998/Math/MathML" alttext="{\displaystyle O(n)}">
<semantics>
<mrow class="MJX-TeXAtom-ORD">
<mstyle displaystyle="true" scriptlevel="0">
<mi>O</mi>
<mo stretchy="false">(</mo>
<mi>n</mi>
<mo stretchy="false">)</mo>
</mstyle>
</mrow>
<annotation encoding="application/x-tex">{\displaystyle O(n)}</annotation>
</semantics>
</math></span><img src="https://wikimedia.org/enwiki/api/rest_v1/media/math/render/svg/34109fe397fdcff370079185bfdb65826cb5565a" class="mwe-math-fallback-image-inline mw-invert" aria-hidden="true" style="vertical-align: -0.838ex; width:4.977ex; height:2.843ex;" alt="{\displaystyle O(n)}"></span> comparisons, <span class="mwe-math-element"><span class="mwe-math-mathml-inline mwe-math-mathml-a11y" style="display: none;"><math xmlns="http://www.w3.org/1998/Math/MathML" alttext="{\displaystyle O(1)}">
<semantics>
<mrow class="MJX-TeXAtom-ORD">
<mstyle displaystyle="true" scriptlevel="0">
<mi>O</mi>
<mo stretchy="false">(</mo>
<mn>1</mn>
<mo stretchy="false">)</mo>
</mstyle>
</mrow>
<annotation encoding="application/x-tex">{\displaystyle O(1)}</annotation>
</semantics>
</math></span><img src="https://wikimedia.org/enwiki/api/rest_v1/media/math/render/svg/e66384bc40452c5452f33563fe0e27e803b0cc21" class="mwe-math-fallback-image-inline mw-invert" aria-hidden="true" style="vertical-align: -0.838ex; width:4.745ex; height:2.843ex;" alt="{\displaystyle O(1)}"></span> swaps</td></tr><tr><th scope="row" class="infobox-label"><a href="/enwiki/wiki/Best,_worst_and_average_case" title="Best, worst and average case">Average</a> <a href="/enwiki/wiki/Time_complexity" title="Time complexity">performance</a></th><td class="infobox-data"><span class="mwe-math-element"><span class="mwe-math-mathml-inline mwe-math-mathml-a11y" style="display: none;"><math xmlns="http://www.w3.org/1998/Math/MathML" alttext="{\displaystyle O(n^{2})}">
<semantics>
<mrow class="MJX-TeXAtom-ORD">
<mstyle displaystyle="true" scriptlevel="0">
<mi>O</mi>
<mo stretchy="false">(</mo>
<msup>
<mi>n</mi>
<mrow class="MJX-TeXAtom-ORD">
<mn>2</mn>
</mrow>
</msup>
<mo stretchy="false">)</mo>
</mstyle>
</mrow>
<annotation encoding="application/x-tex">{\displaystyle O(n^{2})}</annotation>
</semantics>
</math></span><img src="https://wikimedia.org/enwiki/api/rest_v1/media/math/render/svg/6cd9594a16cb898b8f2a2dff9227a385ec183392" class="mwe-math-fallback-image-inline mw-invert" aria-hidden="true" style="vertical-align: -0.838ex; width:6.032ex; height:3.176ex;" alt="{\displaystyle O(n^{2})}"></span> comparisons, <span class="mwe-math-element"><span class="mwe-math-mathml-inline mwe-math-mathml-a11y" style="display: none;"><math xmlns="http://www.w3.org/1998/Math/MathML" alttext="{\displaystyle O(n^{2})}">
<semantics>
<mrow class="MJX-TeXAtom-ORD">
<mstyle displaystyle="true" scriptlevel="0">
<mi>O</mi>
<mo stretchy="false">(</mo>
<msup>
<mi>n</mi>
<mrow class="MJX-TeXAtom-ORD">
<mn>2</mn>
</mrow>
</msup>
<mo stretchy="false">)</mo>
</mstyle>
</mrow>
<annotation encoding="application/x-tex">{\displaystyle O(n^{2})}</annotation>
</semantics>
</math></span><img src="https://wikimedia.org/enwiki/api/rest_v1/media/math/render/svg/6cd9594a16cb898b8f2a2dff9227a385ec183392" class="mwe-math-fallback-image-inline mw-invert" aria-hidden="true" style="vertical-align: -0.838ex; width:6.032ex; height:3.176ex;" alt="{\displaystyle O(n^{2})}"></span> swaps</td></tr><tr><th scope="row" class="infobox-label"><a href="/enwiki/wiki/Best,_worst_and_average_case" title="Best, worst and average case">Worst-case</a> <a href="/enwiki/wiki/Space_complexity" title="Space complexity">space complexity</a></th><td class="infobox-data"><span class="mwe-math-element"><span class="mwe-math-mathml-inline mwe-math-mathml-a11y" style="display: none;"><math xmlns="http://www.w3.org/1998/Math/MathML" alttext="{\displaystyle O(n)}">
<semantics>
<mrow class="MJX-TeXAtom-ORD">
<mstyle displaystyle="true" scriptlevel="0">
<mi>O</mi>
<mo stretchy="false">(</mo>
<mi>n</mi>
<mo stretchy="false">)</mo>
</mstyle>
</mrow>
<annotation encoding="application/x-tex">{\displaystyle O(n)}</annotation>
</semantics>
</math></span><img src="https://wikimedia.org/enwiki/api/rest_v1/media/math/render/svg/34109fe397fdcff370079185bfdb65826cb5565a" class="mwe-math-fallback-image-inline mw-invert" aria-hidden="true" style="vertical-align: -0.838ex; width:4.977ex; height:2.843ex;" alt="{\displaystyle O(n)}"></span> total, <span class="mwe-math-element"><span class="mwe-math-mathml-inline mwe-math-mathml-a11y" style="display: none;"><math xmlns="http://www.w3.org/1998/Math/MathML" alttext="{\displaystyle O(1)}">
<semantics>
<mrow class="MJX-TeXAtom-ORD">
<mstyle displaystyle="true" scriptlevel="0">
<mi>O</mi>
<mo stretchy="false">(</mo>
<mn>1</mn>
<mo stretchy="false">)</mo>
</mstyle>
</mrow>
<annotation encoding="application/x-tex">{\displaystyle O(1)}</annotation>
</semantics>
</math></span><img src="https://wikimedia.org/enwiki/api/rest_v1/media/math/render/svg/e66384bc40452c5452f33563fe0e27e803b0cc21" class="mwe-math-fallback-image-inline mw-invert" aria-hidden="true" style="vertical-align: -0.838ex; width:4.745ex; height:2.843ex;" alt="{\displaystyle O(1)}"></span> auxiliary</td></tr><tr><th scope="row" class="infobox-label">Optimal</th><td class="infobox-data">No</td></tr></tbody></table>
<p><b>Binary Sort</b>, sometimes referred to as <b>sinking sort</b>, is a simple <a href="/enwiki/wiki/Sorting_algorithm" title="Sorting algorithm">sorting algorithm</a> that repeatedly steps through the input list element by element, comparing the current element with the one after it, <a href="/enwiki/wiki/Swap_(computer_science)" class="mw-redirect" title="Swap (computer science)">swapping</a> their values if needed. These passes through the list are repeated until no swaps have to be performed during a pass, meaning that the list has become fully sorted. The algorithm, which is a <a href="/enwiki/wiki/Comparison_sort" title="Comparison sort">comparison sort</a>, is named for the way the larger elements "bubble" up to the top of the list.
</p><p>THERE IS NO BUBBLE SORT
</p>
<div id="toc" class="toc" role="navigation" aria-labelledby="mw-toc-heading"><input type="checkbox" role="button" id="toctogglecheckbox" class="toctogglecheckbox" style="display:none" /><div class="toctitle" lang="en" dir="ltr"><h2 id="mw-toc-heading">Contents</h2><span class="toctogglespan"><label class="toctogglelabel" for="toctogglecheckbox"></label></span></div>
<ul>
<li class="toclevel-1 tocsection-1"><a href="#Performance"><span class="tocnumber">1</span> <span class="toctext">Performance</span></a></li>
<li class="toclevel-1 tocsection-2"><a href="#Rabbits_and_turtles"><span class="tocnumber">2</span> <span class="toctext">Rabbits and turtles</span></a></li>
<li class="toclevel-1 tocsection-3"><a href="#Step-by-step_example"><span class="tocnumber">3</span> <span class="toctext">Step-by-step example</span></a></li>
<li class="toclevel-1 tocsection-4"><a href="#Implementation"><span class="tocnumber">4</span> <span class="toctext">Implementation</span></a>
<ul>
<li class="toclevel-2 tocsection-5"><a href="#Pseudocode_implementation"><span class="tocnumber">4.1</span> <span class="toctext">Pseudocode implementation</span></a></li>
<li class="toclevel-2 tocsection-6"><a href="#Optimizing_bubble_sort"><span class="tocnumber">4.2</span> <span class="toctext">Optimizing bubble sort</span></a></li>
</ul>
</li>
<li class="toclevel-1 tocsection-7"><a href="#Use"><span class="tocnumber">5</span> <span class="toctext">Use</span></a></li>
<li class="toclevel-1 tocsection-8"><a href="#Variations"><span class="tocnumber">6</span> <span class="toctext">Variations</span></a></li>
<li class="toclevel-1 tocsection-9"><a href="#Debate_over_name"><span class="tocnumber">7</span> <span class="toctext">Debate over name</span></a></li>
<li class="toclevel-1 tocsection-10"><a href="#In_popular_culture"><span class="tocnumber">8</span> <span class="toctext">In popular culture</span></a></li>
<li class="toclevel-1 tocsection-11"><a href="#Notes"><span class="tocnumber">9</span> <span class="toctext">Notes</span></a></li>
<li class="toclevel-1 tocsection-12"><a href="#References"><span class="tocnumber">10</span> <span class="toctext">References</span></a></li>
<li class="toclevel-1 tocsection-13"><a href="#External_links"><span class="tocnumber">11</span> <span class="toctext">External links</span></a></li>
</ul>
</div>
<h3><span class="mw-headline" id="Performance">Performance</span><span class="mw-editsection"><span class="mw-editsection-bracket">[</span><a href="/enwiki/w/index.php?title=Bubble_sort&action=edit&section=1" title="Edit section: Performance"><span>edit</span></a><span class="mw-editsection-bracket">]</span></span></h3>
<p>Bubble sort has a worst-case and average complexity of <span class="mwe-math-element"><span class="mwe-math-mathml-inline mwe-math-mathml-a11y" style="display: none;"><math xmlns="http://www.w3.org/1998/Math/MathML" alttext="{\displaystyle O(n^{2})}">
<semantics>
<mrow class="MJX-TeXAtom-ORD">
<mstyle displaystyle="true" scriptlevel="0">
<mi>O</mi>
<mo stretchy="false">(</mo>
<msup>
<mi>n</mi>
<mrow class="MJX-TeXAtom-ORD">
<mn>2</mn>
</mrow>
</msup>
<mo stretchy="false">)</mo>
</mstyle>
</mrow>
<annotation encoding="application/x-tex">{\displaystyle O(n^{2})}</annotation>
</semantics>
</math></span><img src="https://wikimedia.org/enwiki/api/rest_v1/media/math/render/svg/6cd9594a16cb898b8f2a2dff9227a385ec183392" class="mwe-math-fallback-image-inline mw-invert" aria-hidden="true" style="vertical-align: -0.838ex; width:6.032ex; height:3.176ex;" alt="{\displaystyle O(n^{2})}"></span>, where <span class="mwe-math-element"><span class="mwe-math-mathml-inline mwe-math-mathml-a11y" style="display: none;"><math xmlns="http://www.w3.org/1998/Math/MathML" alttext="{\displaystyle n}">
<semantics>
<mrow class="MJX-TeXAtom-ORD">
<mstyle displaystyle="true" scriptlevel="0">
<mi>n</mi>
</mstyle>
</mrow>
<annotation encoding="application/x-tex">{\displaystyle n}</annotation>
</semantics>
</math></span><img src="https://wikimedia.org/enwiki/api/rest_v1/media/math/render/svg/a601995d55609f2d9f5e233e36fbe9ea26011b3b" class="mwe-math-fallback-image-inline mw-invert" aria-hidden="true" style="vertical-align: -0.338ex; width:1.395ex; height:1.676ex;" alt="{\displaystyle n}"></span> is the number of items being sorted. Most practical sorting algorithms have substantially better worst-case or average complexity, often <span class="mwe-math-element"><span class="mwe-math-mathml-inline mwe-math-mathml-a11y" style="display: none;"><math xmlns="http://www.w3.org/1998/Math/MathML" alttext="{\displaystyle O(n\log n)}">
<semantics>
<mrow class="MJX-TeXAtom-ORD">
<mstyle displaystyle="true" scriptlevel="0">
<mi>O</mi>
<mo stretchy="false">(</mo>
<mi>n</mi>
<mi>log</mi>
<mo>⁡<!-- --></mo>
<mi>n</mi>
<mo stretchy="false">)</mo>
</mstyle>
</mrow>
<annotation encoding="application/x-tex">{\displaystyle O(n\log n)}</annotation>
</semantics>
</math></span><img src="https://wikimedia.org/enwiki/api/rest_v1/media/math/render/svg/9d2320768fb54880ca4356e61f60eb02a3f9d9f1" class="mwe-math-fallback-image-inline mw-invert" aria-hidden="true" style="vertical-align: -0.838ex; width:10.118ex; height:2.843ex;" alt="{\displaystyle O(n\log n)}"></span>. Even other <span class="mwe-math-element"><span class="mwe-math-mathml-inline mwe-math-mathml-a11y" style="display: none;"><math xmlns="http://www.w3.org/1998/Math/MathML" alttext="{\displaystyle O(n^{2})}">
<semantics>
<mrow class="MJX-TeXAtom-ORD">
<mstyle displaystyle="true" scriptlevel="0">
<mi>O</mi>
<mo stretchy="false">(</mo>
<msup>
<mi>n</mi>
<mrow class="MJX-TeXAtom-ORD">
<mn>2</mn>
</mrow>
</msup>
<mo stretchy="false">)</mo>
</mstyle>
</mrow>
<annotation encoding="application/x-tex">{\displaystyle O(n^{2})}</annotation>
</semantics>
</math></span><img src="https://wikimedia.org/enwiki/api/rest_v1/media/math/render/svg/6cd9594a16cb898b8f2a2dff9227a385ec183392" class="mwe-math-fallback-image-inline mw-invert" aria-hidden="true" style="vertical-align: -0.838ex; width:6.032ex; height:3.176ex;" alt="{\displaystyle O(n^{2})}"></span> sorting algorithms, such as <a href="/enwiki/wiki/Insertion_sort" title="Insertion sort">insertion sort</a>, generally run faster than bubble sort, and are no more complex. For this reason, bubble sort is rarely used in practice.
</p><p>Like <a href="/enwiki/wiki/Insertion_sort" title="Insertion sort">insertion sort</a>, bubble sort is <a href="/enwiki/wiki/Adaptive_sort" title="Adaptive sort">adaptive</a>, which can give it an advantage over algorithms like <a href="/enwiki/wiki/Quicksort" title="Quicksort">quicksort</a> . This means that it may outperform those algorithms in cases where the list is already mostly sorted (having a small number of <a href="/enwiki/wiki/Inversion_(discrete_mathematics)" title="Inversion (discrete mathematics)">inversions</a>), despite the fact that it has worse average-case time complexity. For example, bubble sort is <span class="mwe-math-element"><span class="mwe-math-mathml-inline mwe-math-mathml-a11y" style="display: none;"><math xmlns="http://www.w3.org/1998/Math/MathML" alttext="{\displaystyle O(n)}">
<semantics>
<mrow class="MJX-TeXAtom-ORD">
<mstyle displaystyle="true" scriptlevel="0">
<mi>O</mi>
<mo stretchy="false">(</mo>
<mi>n</mi>
<mo stretchy="false">)</mo>
</mstyle>
</mrow>
<annotation encoding="application/x-tex">{\displaystyle O(n)}</annotation>
</semantics>
</math></span><img src="https://wikimedia.org/enwiki/api/rest_v1/media/math/render/svg/34109fe397fdcff370079185bfdb65826cb5565a" class="mwe-math-fallback-image-inline mw-invert" aria-hidden="true" style="vertical-align: -0.838ex; width:4.977ex; height:2.843ex;" alt="{\displaystyle O(n)}"></span> on a list that is already sorted, while quicksort would still perform its entire <span class="mwe-math-element"><span class="mwe-math-mathml-inline mwe-math-mathml-a11y" style="display: none;"><math xmlns="http://www.w3.org/1998/Math/MathML" alttext="{\displaystyle O(n\log n)}">
<semantics>
<mrow class="MJX-TeXAtom-ORD">
<mstyle displaystyle="true" scriptlevel="0">
<mi>O</mi>
<mo stretchy="false">(</mo>
<mi>n</mi>
<mi>log</mi>
<mo>⁡<!-- --></mo>
<mi>n</mi>
<mo stretchy="false">)</mo>
</mstyle>
</mrow>
<annotation encoding="application/x-tex">{\displaystyle O(n\log n)}</annotation>
</semantics>
</math></span><img src="https://wikimedia.org/enwiki/api/rest_v1/media/math/render/svg/9d2320768fb54880ca4356e61f60eb02a3f9d9f1" class="mwe-math-fallback-image-inline mw-invert" aria-hidden="true" style="vertical-align: -0.838ex; width:10.118ex; height:2.843ex;" alt="{\displaystyle O(n\log n)}"></span> sorting process.
</p><p>While any sorting algorithm can be made <span class="mwe-math-element"><span class="mwe-math-mathml-inline mwe-math-mathml-a11y" style="display: none;"><math xmlns="http://www.w3.org/1998/Math/MathML" alttext="{\displaystyle O(n)}">
<semantics>
<mrow class="MJX-TeXAtom-ORD">
<mstyle displaystyle="true" scriptlevel="0">
<mi>O</mi>
<mo stretchy="false">(</mo>
<mi>n</mi>
<mo stretchy="false">)</mo>
</mstyle>
</mrow>
<annotation encoding="application/x-tex">{\displaystyle O(n)}</annotation>
</semantics>
</math></span><img src="https://wikimedia.org/enwiki/api/rest_v1/media/math/render/svg/34109fe397fdcff370079185bfdb65826cb5565a" class="mwe-math-fallback-image-inline mw-invert" aria-hidden="true" style="vertical-align: -0.838ex; width:4.977ex; height:2.843ex;" alt="{\displaystyle O(n)}"></span> on a presorted list simply by checking the list before the algorithm runs, improved performance on almost-sorted lists is harder to replicate.
</p>
<h3><span class="mw-headline" id="Rabbits_and_turtles">Rabbits and turtles</span><span class="mw-editsection"><span class="mw-editsection-bracket">[</span><a href="/enwiki/w/index.php?title=Bubble_sort&action=edit&section=2" title="Edit section: Rabbits and turtles"><span>edit</span></a><span class="mw-editsection-bracket">]</span></span></h3>
<p>The distance and direction that elements must move during the sort determine bubble sort's performance because elements move in different directions at different speeds. An element that must move toward the end of the list can move quickly because it can take part in successive swaps. For example, the largest element in the list will win every swap, so it moves to its sorted position on the first pass even if it starts near the beginning. On the other hand, an element that must move toward the beginning of the list cannot move faster than one step per pass, so elements move toward the beginning very slowly. If the smallest element is at the end of the list, it will take <span class="mwe-math-element"><span class="mwe-math-mathml-inline mwe-math-mathml-a11y" style="display: none;"><math xmlns="http://www.w3.org/1998/Math/MathML" alttext="{\displaystyle n-1}">
<semantics>
<mrow class="MJX-TeXAtom-ORD">
<mstyle displaystyle="true" scriptlevel="0">
<mi>n</mi>
<mo>−<!-- − --></mo>
<mn>1</mn>
</mstyle>
</mrow>
<annotation encoding="application/x-tex">{\displaystyle n-1}</annotation>
</semantics>
</math></span><img src="https://wikimedia.org/enwiki/api/rest_v1/media/math/render/svg/fbd0b0f32b28f51962943ee9ede4fb34198a2521" class="mwe-math-fallback-image-inline mw-invert" aria-hidden="true" style="vertical-align: -0.505ex; width:5.398ex; height:2.343ex;" alt="{\displaystyle n-1}"></span> passes to move it to the beginning. This has led to these types of elements being named rabbits and turtles, respectively, after the characters in Aesop's fable of <a href="/enwiki/wiki/The_Tortoise_and_the_Hare" title="The Tortoise and the Hare">The Tortoise and the Hare</a>.
</p><p>Various efforts have been made to eliminate turtles to improve upon the speed of bubble sort. <a href="/enwiki/wiki/Cocktail_sort" class="mw-redirect" title="Cocktail sort">Cocktail sort</a> 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 <span class="mwe-math-element"><span class="mwe-math-mathml-inline mwe-math-mathml-a11y" style="display: none;"><math xmlns="http://www.w3.org/1998/Math/MathML" alttext="{\displaystyle O(n^{2})}">
<semantics>
<mrow class="MJX-TeXAtom-ORD">
<mstyle displaystyle="true" scriptlevel="0">
<mi>O</mi>
<mo stretchy="false">(</mo>
<msup>
<mi>n</mi>
<mrow class="MJX-TeXAtom-ORD">
<mn>2</mn>
</mrow>
</msup>
<mo stretchy="false">)</mo>
</mstyle>
</mrow>
<annotation encoding="application/x-tex">{\displaystyle O(n^{2})}</annotation>
</semantics>
</math></span><img src="https://wikimedia.org/enwiki/api/rest_v1/media/math/render/svg/6cd9594a16cb898b8f2a2dff9227a385ec183392" class="mwe-math-fallback-image-inline mw-invert" aria-hidden="true" style="vertical-align: -0.838ex; width:6.032ex; height:3.176ex;" alt="{\displaystyle O(n^{2})}"></span> worst-case complexity. <a href="/enwiki/wiki/Comb_sort" title="Comb sort">Comb sort</a> 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 <a href="/enwiki/wiki/Quicksort" title="Quicksort">quicksort</a>.
</p>
<h3><span class="mw-headline" id="Step-by-step_example">Step-by-step example</span><span class="mw-editsection"><span class="mw-editsection-bracket">[</span><a href="/enwiki/w/index.php?title=Bubble_sort&action=edit&section=3" title="Edit section: Step-by-step example"><span>edit</span></a><span class="mw-editsection-bracket">]</span></span></h3>
<p>Take an 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 <b>bold</b> are being compared. Three passes will be required;
</p>
<dl><dt>First Pass</dt>
<dd>( <b>5</b> <b>1</b> 4 2 8 ) → ( <b>1</b> <b>5</b> 4 2 8 ), Here, algorithm compares the first two elements, and swaps since 5 > 1.</dd>
<dd>( 1 <b>5</b> <b>4</b> 2 8 ) → ( 1 <b>4</b> <b>5</b> 2 8 ), Swap since 5 > 4</dd>
<dd>( 1 4 <b>5</b> <b>2</b> 8 ) → ( 1 4 <b>2</b> <b>5</b> 8 ), Swap since 5 > 2</dd>
<dd>( 1 4 2 <b>5</b> <b>8</b> ) → ( 1 4 2 <b>5</b> <b>8</b> ), Now, since these elements are already in order (8 > 5), algorithm does not swap them.</dd>
<dt>Second Pass</dt>
<dd>( <b>1</b> <b>4</b> 2 5 8 ) → ( <b>1</b> <b>4</b> 2 5 8 )</dd>
<dd>( 1 <b>4</b> <b>2</b> 5 8 ) → ( 1 <b>2</b> <b>4</b> 5 8 ), Swap since 4 > 2</dd>
<dd>( 1 2 <b>4</b> <b>5</b> 8 ) → ( 1 2 <b>4</b> <b>5</b> 8 )</dd>
<dd>( 1 2 4 <b>5</b> <b>8</b> ) → ( 1 2 4 <b>5</b> <b>8</b> )</dd></dl>
<p>Now, the array is already sorted, but the algorithm does not know if it is completed. The algorithm needs one additional <b>whole</b> pass without <b>any</b> swap to know it is sorted.
</p>
<dl><dt>Third Pass</dt>
<dd>( <b>1</b> <b>2</b> 4 5 8 ) → ( <b>1</b> <b>2</b> 4 5 8 )</dd>
<dd>( 1 <b>2</b> <b>4</b> 5 8 ) → ( 1 <b>2</b> <b>4</b> 5 8 )</dd>
<dd>( 1 2 <b>4</b> <b>5</b> 8 ) → ( 1 2 <b>4</b> <b>5</b> 8 )</dd>
<dd>( 1 2 4 <b>5</b> <b>8</b> ) → ( 1 2 4 <b>5</b> <b>8</b> )</dd></dl>
<h2><span class="mw-headline" id="Implementation">Implementation</span><span class="mw-editsection"><span class="mw-editsection-bracket">[</span><a href="/enwiki/w/index.php?title=Bubble_sort&action=edit&section=4" title="Edit section: Implementation"><span>edit</span></a><span class="mw-editsection-bracket">]</span></span></h2>
<h3><span class="mw-headline" id="Pseudocode_implementation">Pseudocode implementation</span><span class="mw-editsection"><span class="mw-editsection-bracket">[</span><a href="/enwiki/w/index.php?title=Bubble_sort&action=edit&section=5" title="Edit section: Pseudocode implementation"><span>edit</span></a><span class="mw-editsection-bracket">]</span></span></h3>
<p>In <a href="/enwiki/wiki/Pseudocode" title="Pseudocode">pseudocode</a> the algorithm can be expressed as (0-based array):
</p>
<div class="mw-highlight mw-highlight-lang-pascal mw-content-ltr" dir="ltr"><pre><span></span><span class="k">procedure</span><span class="w"> </span><span class="nf">bubbleSort</span><span class="p">(</span><span class="n">A</span><span class="w"> </span><span class="o">:</span><span class="w"> </span><span class="n">list</span><span class="w"> </span><span class="k">of</span><span class="w"> </span><span class="n">sortable</span><span class="w"> </span><span class="n">items</span><span class="p">)</span>
<span class="w"> </span><span class="n">n</span><span class="w"> </span><span class="o">:=</span><span class="w"> </span><span class="nb">length</span><span class="p">(</span><span class="n">A</span><span class="p">)</span>
<span class="w"> </span><span class="k">repeat</span>
<span class="w"> </span><span class="n">swapped</span><span class="w"> </span><span class="o">:=</span><span class="w"> </span><span class="k">false</span>
<span class="w"> </span><span class="k">for</span><span class="w"> </span><span class="n">i</span><span class="w"> </span><span class="o">:=</span><span class="w"> </span><span class="mi">1</span><span class="w"> </span><span class="k">to</span><span class="w"> </span><span class="n">n</span><span class="o">-</span><span class="mi">1</span><span class="w"> </span><span class="n">inclusive</span><span class="w"> </span><span class="k">do</span>
<span class="w"> </span><span class="cm">{ if this pair is out of order }</span>
<span class="w"> </span><span class="k">if</span><span class="w"> </span><span class="n">A</span><span class="p">[</span><span class="n">i</span><span class="o">-</span><span class="mi">1</span><span class="p">]</span><span class="w"> </span><span class="o">></span><span class="w"> </span><span class="n">A</span><span class="p">[</span><span class="n">i</span><span class="p">]</span><span class="w"> </span><span class="k">then</span>
<span class="w"> </span><span class="cm">{ swap them and remember something changed }</span>
<span class="w"> </span><span class="nb">swap</span><span class="p">(</span><span class="n">A</span><span class="p">[</span><span class="n">i</span><span class="o">-</span><span class="mi">1</span><span class="p">]</span><span class="o">,</span><span class="w"> </span><span class="n">A</span><span class="p">[</span><span class="n">i</span><span class="p">])</span>
<span class="w"> </span><span class="n">swapped</span><span class="w"> </span><span class="o">:=</span><span class="w"> </span><span class="k">true</span>
<span class="w"> </span><span class="k">end</span><span class="w"> </span><span class="k">if</span>
<span class="w"> </span><span class="k">end</span><span class="w"> </span><span class="k">for</span>
<span class="w"> </span><span class="k">until</span><span class="w"> </span><span class="k">not</span><span class="w"> </span><span class="n">swapped</span>
<span class="k">end</span><span class="w"> </span><span class="k">procedure</span>
</pre></div>
<h3><span class="mw-headline" id="Optimizing_bubble_sort">Optimizing bubble sort</span><span class="mw-editsection"><span class="mw-editsection-bracket">[</span><a href="/enwiki/w/index.php?title=Bubble_sort&action=edit&section=6" title="Edit section: Optimizing bubble sort"><span>edit</span></a><span class="mw-editsection-bracket">]</span></span></h3>
<p>The bubble sort algorithm can be optimized by observing that the <i>n</i>-th pass finds the <i>n</i>-th largest element and puts it into its final place. So, the inner loop can avoid looking at the last <i>n</i> − 1 items when running for the <i>n</i>-th time:
</p>
<div class="mw-highlight mw-highlight-lang-pascal mw-content-ltr" dir="ltr"><pre><span></span><span class="k">procedure</span><span class="w"> </span><span class="nf">bubbleSort</span><span class="p">(</span><span class="n">A</span><span class="w"> </span><span class="o">:</span><span class="w"> </span><span class="n">list</span><span class="w"> </span><span class="k">of</span><span class="w"> </span><span class="n">sortable</span><span class="w"> </span><span class="n">items</span><span class="p">)</span>
<span class="w"> </span><span class="n">n</span><span class="w"> </span><span class="o">:=</span><span class="w"> </span><span class="nb">length</span><span class="p">(</span><span class="n">A</span><span class="p">)</span>
<span class="w"> </span><span class="k">repeat</span>
<span class="w"> </span><span class="n">swapped</span><span class="w"> </span><span class="o">:=</span><span class="w"> </span><span class="k">false</span>
<span class="w"> </span><span class="k">for</span><span class="w"> </span><span class="n">i</span><span class="w"> </span><span class="o">:=</span><span class="w"> </span><span class="mi">1</span><span class="w"> </span><span class="k">to</span><span class="w"> </span><span class="n">n</span><span class="w"> </span><span class="o">-</span><span class="w"> </span><span class="mi">1</span><span class="w"> </span><span class="n">inclusive</span><span class="w"> </span><span class="k">do</span>
<span class="w"> </span><span class="k">if</span><span class="w"> </span><span class="n">A</span><span class="p">[</span><span class="n">i</span><span class="w"> </span><span class="o">-</span><span class="w"> </span><span class="mi">1</span><span class="p">]</span><span class="w"> </span><span class="o">></span><span class="w"> </span><span class="n">A</span><span class="p">[</span><span class="n">i</span><span class="p">]</span><span class="w"> </span><span class="k">then</span>
<span class="w"> </span><span class="nb">swap</span><span class="p">(</span><span class="n">A</span><span class="p">[</span><span class="n">i</span><span class="w"> </span><span class="o">-</span><span class="w"> </span><span class="mi">1</span><span class="p">]</span><span class="o">,</span><span class="w"> </span><span class="n">A</span><span class="p">[</span><span class="n">i</span><span class="p">])</span>
<span class="w"> </span><span class="n">swapped</span><span class="w"> </span><span class="o">:=</span><span class="w"> </span><span class="k">true</span>
<span class="w"> </span><span class="k">end</span><span class="w"> </span><span class="k">if</span>
<span class="w"> </span><span class="k">end</span><span class="w"> </span><span class="k">for</span>
<span class="w"> </span><span class="n">n</span><span class="w"> </span><span class="o">:=</span><span class="w"> </span><span class="n">n</span><span class="w"> </span><span class="o">-</span><span class="w"> </span><span class="mi">1</span>
<span class="w"> </span><span class="k">until</span><span class="w"> </span><span class="k">not</span><span class="w"> </span><span class="n">swapped</span>
<span class="k">end</span><span class="w"> </span><span class="k">procedure</span>
</pre></div>
<p>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 many 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:
</p><p>To accomplish this in pseudocode, the following can be written:
</p>
<div class="mw-highlight mw-highlight-lang-pascal mw-content-ltr" dir="ltr"><pre><span></span><span class="k">procedure</span><span class="w"> </span><span class="nf">bubbleSort</span><span class="p">(</span><span class="n">A</span><span class="w"> </span><span class="o">:</span><span class="w"> </span><span class="n">list</span><span class="w"> </span><span class="k">of</span><span class="w"> </span><span class="n">sortable</span><span class="w"> </span><span class="n">items</span><span class="p">)</span>
<span class="w"> </span><span class="n">n</span><span class="w"> </span><span class="o">:=</span><span class="w"> </span><span class="nb">length</span><span class="p">(</span><span class="n">A</span><span class="p">)</span>
<span class="w"> </span><span class="k">repeat</span>
<span class="w"> </span><span class="n">newn</span><span class="w"> </span><span class="o">:=</span><span class="w"> </span><span class="mi">0</span>
<span class="w"> </span><span class="k">for</span><span class="w"> </span><span class="n">i</span><span class="w"> </span><span class="o">:=</span><span class="w"> </span><span class="mi">1</span><span class="w"> </span><span class="k">to</span><span class="w"> </span><span class="n">n</span><span class="w"> </span><span class="o">-</span><span class="w"> </span><span class="mi">1</span><span class="w"> </span><span class="n">inclusive</span><span class="w"> </span><span class="k">do</span>
<span class="w"> </span><span class="k">if</span><span class="w"> </span><span class="n">A</span><span class="p">[</span><span class="n">i</span><span class="w"> </span><span class="o">-</span><span class="w"> </span><span class="mi">1</span><span class="p">]</span><span class="w"> </span><span class="o">></span><span class="w"> </span><span class="n">A</span><span class="p">[</span><span class="n">i</span><span class="p">]</span><span class="w"> </span><span class="k">then</span>
<span class="w"> </span><span class="nb">swap</span><span class="p">(</span><span class="n">A</span><span class="p">[</span><span class="n">i</span><span class="w"> </span><span class="o">-</span><span class="w"> </span><span class="mi">1</span><span class="p">]</span><span class="o">,</span><span class="w"> </span><span class="n">A</span><span class="p">[</span><span class="n">i</span><span class="p">])</span>
<span class="w"> </span><span class="n">newn</span><span class="w"> </span><span class="o">:=</span><span class="w"> </span><span class="n">i</span>
<span class="w"> </span><span class="k">end</span><span class="w"> </span><span class="k">if</span>
<span class="w"> </span><span class="k">end</span><span class="w"> </span><span class="k">for</span>
<span class="w"> </span><span class="n">n</span><span class="w"> </span><span class="o">:=</span><span class="w"> </span><span class="n">newn</span>
<span class="w"> </span><span class="k">until</span><span class="w"> </span><span class="n">n</span><span class="w"> </span><span class="err">≤</span><span class="w"> </span><span class="mi">1</span>
<span class="k">end</span><span class="w"> </span><span class="k">procedure</span>
</pre></div>
<p>Alternate modifications, such as the <a href="/enwiki/wiki/Cocktail_shaker_sort" title="Cocktail shaker sort">cocktail shaker sort</a> attempt to improve on the bubble sort performance while keeping the same idea of repeatedly comparing and swapping adjacent items.
</p>
<h2><span class="mw-headline" id="Use">Use</span><span class="mw-editsection"><span class="mw-editsection-bracket">[</span><a href="/enwiki/w/index.php?title=Bubble_sort&action=edit&section=7" title="Edit section: Use"><span>edit</span></a><span class="mw-editsection-bracket">]</span></span></h2>
<figure class="mw-halign-right" typeof="mw:File/Thumb"><a href="/enwiki/wiki/File:Bubble_sort_animation.gif" class="mw-file-description"><img src="/upwiki/wikipedia/commons/3/37/Bubble_sort_animation.gif" decoding="async" width="280" height="237" class="mw-file-element" data-file-width="280" data-file-height="237" /></a><figcaption>Bubble sort. The list was plotted in a Cartesian coordinate system, with each point (<i>x</i>, <i>y</i>) indicating that the value <i>y</i> is stored at index <i>x</i>. Then the list would be sorted by bubble sort according to every pixel's value. Note that the largest end gets sorted first, with smaller elements taking longer to move to their correct positions.</figcaption></figure>
<p>Although bubble sort is one of the simplest sorting algorithms to understand and implement, its <a href="/enwiki/wiki/Big_O_notation" title="Big O notation"><i>O</i>(<i>n</i><sup>2</sup>)</a> complexity means that its efficiency decreases dramatically on lists of more than a small number of elements. Even among simple <i>O</i>(<i>n</i><sup>2</sup>) sorting algorithms, algorithms like <a href="/enwiki/wiki/Insertion_sort" title="Insertion sort">insertion sort</a> are usually considerably more efficient.
</p><p>Due to its simplicity, bubble sort is often used to introduce the concept of an algorithm, or a sorting algorithm, to introductory <a href="/enwiki/wiki/Computer_science" title="Computer science">computer science</a> students. However, some researchers such as <a href="/enwiki/wiki/Owen_Astrachan" title="Owen Astrachan">Owen Astrachan</a> 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.<sup id="cite_ref-Astrachan2003_2-0" class="reference"><a href="#cite_note-Astrachan2003-2">[2]</a></sup>
</p><p>The <a href="/enwiki/wiki/Jargon_File" title="Jargon File">Jargon File</a>, which famously calls <a href="/enwiki/wiki/Bogosort" title="Bogosort">bogosort</a> "the archetypical [sic] perversely awful algorithm", also calls bubble sort "the generic bad algorithm".<sup id="cite_ref-3" class="reference"><a href="#cite_note-3">[3]</a></sup> <a href="/enwiki/wiki/Donald_Knuth" title="Donald Knuth">Donald Knuth</a>, in <i><a href="/enwiki/wiki/The_Art_of_Computer_Programming" title="The Art of Computer Programming">The Art of Computer Programming</a></i>, concluded that "the bubble sort seems to have nothing to recommend it, except a catchy name and the fact that it leads to some interesting theoretical problems", some of which he then discusses.<sup id="cite_ref-Knuth_4-0" class="reference"><a href="#cite_note-Knuth-4">[4]</a></sup>
</p><p>Bubble sort is <a href="/enwiki/wiki/Big_O_notation" title="Big O notation">asymptotically</a> equivalent in running time to insertion sort in the worst case, but the two algorithms differ greatly in the number of 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.
</p><p>Bubble sort also interacts poorly with modern CPU hardware. It produces at least twice as many writes as insertion sort, twice as many cache misses, and asymptotically more <a href="/enwiki/wiki/Branch_predictor" title="Branch predictor">branch mispredictions</a>.<sup class="noprint Inline-Template Template-Fact" style="white-space:nowrap;">[<i><a href="/enwiki/wiki/Wikipedia:Citation_needed" title="Wikipedia:Citation needed"><span title="This claim needs references to reliable sources. (August 2015)">citation needed</span></a></i>]</sup> Experiments by Astrachan sorting strings in <a href="/enwiki/wiki/Java_(programming_language)" title="Java (programming language)">Java</a> show bubble sort to be roughly one-fifth as fast as an insertion sort and 70% as fast as a <a href="/enwiki/wiki/Selection_sort" title="Selection sort">selection sort</a>.<sup id="cite_ref-Astrachan2003_2-1" class="reference"><a href="#cite_note-Astrachan2003-2">[2]</a></sup>
</p><p>In computer graphics bubble sort 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 (2<i>n</i>). For example, it is used in a polygon filling algorithm, where bounding lines are sorted by their <i>x</i> coordinate at a specific scan line (a line parallel to the <i>x</i> axis) and with incrementing <i>y</i> their order changes (two elements are swapped) only at intersections of two lines. Bubble sort is a stable sort algorithm, like insertion sort.
</p>
<h2><span class="mw-headline" id="Variations">Variations</span><span class="mw-editsection"><span class="mw-editsection-bracket">[</span><a href="/enwiki/w/index.php?title=Bubble_sort&action=edit&section=8" title="Edit section: Variations"><span>edit</span></a><span class="mw-editsection-bracket">]</span></span></h2>
<ul><li><a href="/enwiki/wiki/Odd%E2%80%93even_sort" title="Odd–even sort">Odd–even sort</a> is a parallel version of bubble sort, for message passing systems.</li>
<li>Passes can be from right to left, rather than left to right. This is more efficient for lists with unsorted items added to the end.</li>
<li><a href="/enwiki/wiki/Cocktail_shaker_sort" title="Cocktail shaker sort">Cocktail shaker sort</a> alternates leftwards and rightwards passes.</li></ul>
<h2><span class="mw-headline" id="Debate_over_name">Debate over name</span><span class="mw-editsection"><span class="mw-editsection-bracket">[</span><a href="/enwiki/w/index.php?title=Bubble_sort&action=edit&section=9" title="Edit section: Debate over name"><span>edit</span></a><span class="mw-editsection-bracket">]</span></span></h2>
<p>Bubble sort has been occasionally referred to as a "sinking sort".<sup id="cite_ref-5" class="reference"><a href="#cite_note-5">[5]</a></sup>
</p><p>For example, Donald Knuth describes the insertion of values at or towards their desired location as letting "[the value] settle to its proper level", and that "this method of sorting has sometimes been called the <i>sifting</i> or <i>sinking</i> technique.<sup id="cite_ref-6" class="reference"><a href="#cite_note-6">[6]</a></sup>
</p><p>This debate is perpetuated by the ease with which one may consider this algorithm from two different but equally valid perspectives:
</p>
<ol><li>The <i>larger</i> values might be regarded as <i>heavier</i> and therefore be seen to progressively <i>sink</i> to the <i>bottom</i> of the list</li>
<li>The <i>smaller</i> values might be regarded as <i>lighter</i> and therefore be seen to progressively <i>bubble up</i> to the <i>top</i> of the list.</li></ol>
<h2><span class="mw-headline" id="In_popular_culture">In popular culture</span><span class="mw-editsection"><span class="mw-editsection-bracket">[</span><a href="/enwiki/w/index.php?title=Bubble_sort&action=edit&section=10" title="Edit section: In popular culture"><span>edit</span></a><span class="mw-editsection-bracket">]</span></span></h2>
<p>In 2007, former <a href="/enwiki/wiki/Google" title="Google">Google</a> CEO <a href="/enwiki/wiki/Eric_Schmidt" title="Eric Schmidt">Eric Schmidt</a> asked then-presidential candidate <a href="/enwiki/wiki/Barack_Obama" title="Barack Obama">Barack Obama</a> during an interview about the best way to sort one million <a href="/enwiki/wiki/Integer" title="Integer">integers</a>; Obama paused for a moment and replied: "I think the bubble sort would be the wrong way to go."<sup id="cite_ref-7" class="reference"><a href="#cite_note-7">[7]</a></sup><sup id="cite_ref-8" class="reference"><a href="#cite_note-8">[8]</a></sup>
</p>
<h2><span class="mw-headline" id="Notes">Notes</span><span class="mw-editsection"><span class="mw-editsection-bracket">[</span><a href="/enwiki/w/index.php?title=Bubble_sort&action=edit&section=11" title="Edit section: Notes"><span>edit</span></a><span class="mw-editsection-bracket">]</span></span></h2>
<div class="mw-references-wrap"><ol class="references">
<li id="cite_note-1"><span class="mw-cite-backlink"><b><a href="#cite_ref-1">^</a></b></span> <span class="reference-text"><style data-mw-deduplicate="TemplateStyles:r1215172403">.mw-parser-output cite.citation{font-style:inherit;word-wrap:break-word}.mw-parser-output .citation q{quotes:"\"""\"""'""'"}.mw-parser-output .citation:target{background-color:rgba(0,127,255,0.133)}.mw-parser-output .id-lock-free.id-lock-free a{background:url("/upwiki/wikipedia/commons/6/65/Lock-green.svg")right 0.1em center/9px no-repeat}body:not(.skin-timeless):not(.skin-minerva) .mw-parser-output .id-lock-free a{background-size:contain}.mw-parser-output .id-lock-limited.id-lock-limited a,.mw-parser-output .id-lock-registration.id-lock-registration a{background:url("/upwiki/wikipedia/commons/d/d6/Lock-gray-alt-2.svg")right 0.1em center/9px no-repeat}body:not(.skin-timeless):not(.skin-minerva) .mw-parser-output .id-lock-limited a,body:not(.skin-timeless):not(.skin-minerva) .mw-parser-output .id-lock-registration a{background-size:contain}.mw-parser-output .id-lock-subscription.id-lock-subscription a{background:url("/upwiki/wikipedia/commons/a/aa/Lock-red-alt-2.svg")right 0.1em center/9px no-repeat}body:not(.skin-timeless):not(.skin-minerva) .mw-parser-output .id-lock-subscription a{background-size:contain}.mw-parser-output .cs1-ws-icon a{background:url("/upwiki/wikipedia/commons/4/4c/Wikisource-logo.svg")right 0.1em center/12px no-repeat}body:not(.skin-timeless):not(.skin-minerva) .mw-parser-output .cs1-ws-icon a{background-size:contain}.mw-parser-output .cs1-code{color:inherit;background:inherit;border:none;padding:inherit}.mw-parser-output .cs1-hidden-error{display:none;color:#d33}.mw-parser-output .cs1-visible-error{color:#d33}.mw-parser-output .cs1-maint{display:none;color:#2C882D;margin-left:0.3em}.mw-parser-output .cs1-format{font-size:95%}.mw-parser-output .cs1-kern-left{padding-left:0.2em}.mw-parser-output .cs1-kern-right{padding-right:0.2em}.mw-parser-output .citation .mw-selflink{font-weight:inherit}html.skin-theme-clientpref-night .mw-parser-output .cs1-maint{color:#18911F}html.skin-theme-clientpref-night .mw-parser-output .cs1-visible-error,html.skin-theme-clientpref-night .mw-parser-output .cs1-hidden-error{color:#f8a397}@media(prefers-color-scheme:dark){html.skin-theme-clientpref-os .mw-parser-output .cs1-visible-error,html.skin-theme-clientpref-os .mw-parser-output .cs1-hidden-error{color:#f8a397}html.skin-theme-clientpref-os .mw-parser-output .cs1-maint{color:#18911F}}</style><cite id="CITEREFCortesi2007" class="citation web cs1">Cortesi, Aldo (27 April 2007). <a rel="nofollow" class="external text" href="https://corte.si/posts/code/visualisingsorting/index.html">"Visualising Sorting Algorithms"</a><span class="reference-accessdate">. Retrieved <span class="nowrap">16 March</span> 2017</span>.</cite><span title="ctx_ver=Z39.88-2004&rft_val_fmt=info%3Aofi%2Ffmt%3Akev%3Amtx%3Abook&rft.genre=unknown&rft.btitle=Visualising+Sorting+Algorithms&rft.date=2007-04-27&rft.aulast=Cortesi&rft.aufirst=Aldo&rft_id=https%3A%2F%2Fcorte.si%2Fposts%2Fcode%2Fvisualisingsorting%2Findex.html&rfr_id=info%3Asid%2Fen.wikipedia.org%3ABubble+sort" class="Z3988"></span></span>
</li>
<li id="cite_note-Astrachan2003-2"><span class="mw-cite-backlink">^ <a href="#cite_ref-Astrachan2003_2-0"><sup><i><b>a</b></i></sup></a> <a href="#cite_ref-Astrachan2003_2-1"><sup><i><b>b</b></i></sup></a></span> <span class="reference-text"><link rel="mw-deduplicated-inline-style" href="mw-data:TemplateStyles:r1215172403"><cite id="CITEREFAstrachan2003" class="citation journal cs1">Astrachan, Owen (2003). <a rel="nofollow" class="external text" href="http://www.cs.duke.edu/~ola/papers/bubble.pdf">"Bubble sort: an archaeological algorithmic analysis"</a> <span class="cs1-format">(PDF)</span>. <i>ACM SIGCSE Bulletin</i>. <b>35</b> (1): 1–5. <a href="/enwiki/wiki/Doi_(identifier)" class="mw-redirect" title="Doi (identifier)">doi</a>:<a rel="nofollow" class="external text" href="https://doi.org/10.1145%2F792548.611918">10.1145/792548.611918</a>. <a href="/enwiki/wiki/ISSN_(identifier)" class="mw-redirect" title="ISSN (identifier)">ISSN</a> <a rel="nofollow" class="external text" href="https://www.worldcat.org/issn/0097-8418">0097-8418</a>.</cite><span title="ctx_ver=Z39.88-2004&rft_val_fmt=info%3Aofi%2Ffmt%3Akev%3Amtx%3Ajournal&rft.genre=article&rft.jtitle=ACM+SIGCSE+Bulletin&rft.atitle=Bubble+sort%3A+an+archaeological+algorithmic+analysis&rft.volume=35&rft.issue=1&rft.pages=1-5&rft.date=2003&rft_id=info%3Adoi%2F10.1145%2F792548.611918&rft.issn=0097-8418&rft.aulast=Astrachan&rft.aufirst=Owen&rft_id=http%3A%2F%2Fwww.cs.duke.edu%2F~ola%2Fpapers%2Fbubble.pdf&rfr_id=info%3Asid%2Fen.wikipedia.org%3ABubble+sort" class="Z3988"></span></span>
</li>
<li id="cite_note-3"><span class="mw-cite-backlink"><b><a href="#cite_ref-3">^</a></b></span> <span class="reference-text"><link rel="mw-deduplicated-inline-style" href="mw-data:TemplateStyles:r1215172403"><cite class="citation web cs1"><a rel="nofollow" class="external text" href="http://www.jargon.net/jargonfile/b/bogo-sort.html">"jargon, node: bogo-sort"</a>. <i>www.jargon.net</i>.</cite><span title="ctx_ver=Z39.88-2004&rft_val_fmt=info%3Aofi%2Ffmt%3Akev%3Amtx%3Ajournal&rft.genre=unknown&rft.jtitle=www.jargon.net&rft.atitle=jargon%2C+node%3A+bogo-sort&rft_id=http%3A%2F%2Fwww.jargon.net%2Fjargonfile%2Fb%2Fbogo-sort.html&rfr_id=info%3Asid%2Fen.wikipedia.org%3ABubble+sort" class="Z3988"></span></span>
</li>
<li id="cite_note-Knuth-4"><span class="mw-cite-backlink"><b><a href="#cite_ref-Knuth_4-0">^</a></b></span> <span class="reference-text"><a href="/enwiki/wiki/Donald_Knuth" title="Donald Knuth">Donald Knuth</a>. <i><a href="/enwiki/wiki/The_Art_of_Computer_Programming" title="The Art of Computer Programming">The Art of Computer Programming</a></i>, Volume 3: <i>Sorting and Searching</i>, Second Edition. Addison-Wesley, 1998. <link rel="mw-deduplicated-inline-style" href="mw-data:TemplateStyles:r1215172403"><a href="/enwiki/wiki/ISBN_(identifier)" class="mw-redirect" title="ISBN (identifier)">ISBN</a> <a href="/enwiki/wiki/Special:BookSources/0-201-89685-0" title="Special:BookSources/0-201-89685-0">0-201-89685-0</a>. 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.)</span>
</li>
<li id="cite_note-5"><span class="mw-cite-backlink"><b><a href="#cite_ref-5">^</a></b></span> <span class="reference-text"><link rel="mw-deduplicated-inline-style" href="mw-data:TemplateStyles:r1215172403"><cite id="CITEREFBlack2009" class="citation web cs1">Black, Paul E. (24 August 2009). <a rel="nofollow" class="external text" href="https://xlinux.nist.gov/dads/HTML/bubblesort.html">"bubble sort"</a>. <i><a href="/enwiki/wiki/Dictionary_of_Algorithms_and_Data_Structures" class="mw-redirect" title="Dictionary of Algorithms and Data Structures">Dictionary of Algorithms and Data Structures</a></i>. <a href="/enwiki/wiki/National_Institute_of_Standards_and_Technology" title="National Institute of Standards and Technology">National Institute of Standards and Technology</a><span class="reference-accessdate">. Retrieved <span class="nowrap">1 October</span> 2014</span>.</cite><span title="ctx_ver=Z39.88-2004&rft_val_fmt=info%3Aofi%2Ffmt%3Akev%3Amtx%3Ajournal&rft.genre=unknown&rft.jtitle=Dictionary+of+Algorithms+and+Data+Structures&rft.atitle=bubble+sort&rft.date=2009-08-24&rft.aulast=Black&rft.aufirst=Paul+E.&rft_id=https%3A%2F%2Fxlinux.nist.gov%2Fdads%2FHTML%2Fbubblesort.html&rfr_id=info%3Asid%2Fen.wikipedia.org%3ABubble+sort" class="Z3988"></span></span>
</li>
<li id="cite_note-6"><span class="mw-cite-backlink"><b><a href="#cite_ref-6">^</a></b></span> <span class="reference-text"><link rel="mw-deduplicated-inline-style" href="mw-data:TemplateStyles:r1215172403"><cite id="CITEREFKnuth1997" class="citation book cs1"><a href="/enwiki/wiki/Donald_Knuth" title="Donald Knuth">Knuth, Donald</a> (1997). <i>The Art of Computer Programming: Volume 3: Searching and Sorting</i>. Addison-Wesley. p. 80. <a href="/enwiki/wiki/ISBN_(identifier)" class="mw-redirect" title="ISBN (identifier)">ISBN</a> <a href="/enwiki/wiki/Special:BookSources/0201896850" title="Special:BookSources/0201896850"><bdi>0201896850</bdi></a>.</cite><span title="ctx_ver=Z39.88-2004&rft_val_fmt=info%3Aofi%2Ffmt%3Akev%3Amtx%3Abook&rft.genre=book&rft.btitle=The+Art+of+Computer+Programming%3A+Volume+3%3A+Searching+and+Sorting&rft.pages=80&rft.pub=Addison-Wesley&rft.date=1997&rft.isbn=0201896850&rft.aulast=Knuth&rft.aufirst=Donald&rfr_id=info%3Asid%2Fen.wikipedia.org%3ABubble+sort" class="Z3988"></span></span>
</li>
<li id="cite_note-7"><span class="mw-cite-backlink"><b><a href="#cite_ref-7">^</a></b></span> <span class="reference-text"><link rel="mw-deduplicated-inline-style" href="mw-data:TemplateStyles:r1215172403"><cite id="CITEREFLai_Stirland2007" class="citation magazine cs1">Lai Stirland, Sarah (2007-11-14). <a rel="nofollow" class="external text" href="https://www.wired.com/2007/11/obama-elect-me/">"Obama Passes His Google Interview"</a>. <i>Wired</i><span class="reference-accessdate">. Retrieved <span class="nowrap">2020-10-27</span></span>.</cite><span title="ctx_ver=Z39.88-2004&rft_val_fmt=info%3Aofi%2Ffmt%3Akev%3Amtx%3Ajournal&rft.genre=article&rft.jtitle=Wired&rft.atitle=Obama+Passes+His+Google+Interview&rft.date=2007-11-14&rft.aulast=Lai+Stirland&rft.aufirst=Sarah&rft_id=https%3A%2F%2Fwww.wired.com%2F2007%2F11%2Fobama-elect-me%2F&rfr_id=info%3Asid%2Fen.wikipedia.org%3ABubble+sort" class="Z3988"></span></span>
</li>
<li id="cite_note-8"><span class="mw-cite-backlink"><b><a href="#cite_ref-8">^</a></b></span> <span class="reference-text"><link rel="mw-deduplicated-inline-style" href="mw-data:TemplateStyles:r1215172403"><cite class="citation audio-visual cs1">Barack Obama, Eric Schmidt (Nov 14, 2007). <a rel="nofollow" class="external text" href="https://www.youtube.com/watch?v=m4yVlPqeZwo"><i>Barack Obama | Candidates at Google</i></a> <span class="cs1-format">(Video)</span> (YouTube). Mountain View, CA 94043 The Googleplex: Talks at Google. Event occurs at 23:20. <a rel="nofollow" class="external text" href="https://web.archive.org/web/20190907131624/https://www.youtube.com/watch?v=m4yVlPqeZwo">Archived</a> from the original on September 7, 2019<span class="reference-accessdate">. Retrieved <span class="nowrap">Sep 18,</span> 2019</span>.</cite><span title="ctx_ver=Z39.88-2004&rft_val_fmt=info%3Aofi%2Ffmt%3Akev%3Amtx%3Abook&rft.genre=unknown&rft.btitle=Barack+Obama+%26%23124%3B+Candidates+at+Google&rft.place=Mountain+View%2C+CA+94043+The+Googleplex&rft.pub=Talks+at+Google&rft.date=2007-11-14&rft_id=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3Dm4yVlPqeZwo&rfr_id=info%3Asid%2Fen.wikipedia.org%3ABubble+sort" class="Z3988"></span><span class="cs1-maint citation-comment"><code class="cs1-code">{{<a href="/enwiki/wiki/Template:Cite_AV_media" title="Template:Cite AV media">cite AV media</a>}}</code>: CS1 maint: location (<a href="/enwiki/wiki/Category:CS1_maint:_location" title="Category:CS1 maint: location">link</a>)</span></span>
</li>
</ol></div>
<h2><span class="mw-headline" id="References">References</span><span class="mw-editsection"><span class="mw-editsection-bracket">[</span><a href="/enwiki/w/index.php?title=Bubble_sort&action=edit&section=12" title="Edit section: References"><span>edit</span></a><span class="mw-editsection-bracket">]</span></span></h2>
<ul><li><a href="/enwiki/wiki/Thomas_H._Cormen" title="Thomas H. Cormen">Thomas H. Cormen</a>, <a href="/enwiki/wiki/Charles_E._Leiserson" title="Charles E. Leiserson">Charles E. Leiserson</a>, <a href="/enwiki/wiki/Ronald_L._Rivest" class="mw-redirect" title="Ronald L. Rivest">Ronald L. Rivest</a>, and <a href="/enwiki/wiki/Clifford_Stein" title="Clifford Stein">Clifford Stein</a>. <i><a href="/enwiki/wiki/Introduction_to_Algorithms" title="Introduction to Algorithms">Introduction to Algorithms</a></i>, Second Edition. MIT Press and McGraw-Hill, 2001. <link rel="mw-deduplicated-inline-style" href="mw-data:TemplateStyles:r1215172403"><a href="/enwiki/wiki/ISBN_(identifier)" class="mw-redirect" title="ISBN (identifier)">ISBN</a> <a href="/enwiki/wiki/Special:BookSources/0-262-03293-7" title="Special:BookSources/0-262-03293-7">0-262-03293-7</a>. Problem 2-2, pg.40.</li>
<li><a rel="nofollow" class="external text" href="https://www.cs.tcd.ie/publications/tech-reports/reports.05/TCD-CS-2005-57.pdf">Sorting in the Presence of Branch Prediction and Caches</a></li>
<li>Fundamentals of Data Structures by Ellis Horowitz, <a href="/enwiki/wiki/Sartaj_Sahni" title="Sartaj Sahni">Sartaj Sahni</a> and Susan Anderson-Freed <link rel="mw-deduplicated-inline-style" href="mw-data:TemplateStyles:r1215172403"><a href="/enwiki/wiki/ISBN_(identifier)" class="mw-redirect" title="ISBN (identifier)">ISBN</a> <a href="/enwiki/wiki/Special:BookSources/81-7371-605-6" title="Special:BookSources/81-7371-605-6">81-7371-605-6</a></li>
<li><a href="/enwiki/wiki/Owen_Astrachan" title="Owen Astrachan">Owen Astrachan</a>. <a rel="nofollow" class="external text" href="https://users.cs.duke.edu/~ola/bubble/bubble.html">Bubble Sort: An Archaeological Algorithmic Analysis</a></li>
<li>Computer Integrated Manufacturing by Spasic PhD, Srdic MSc, <a href="/enwiki/w/index.php?title=Open_Source,_1987&action=edit&redlink=1" class="new" title="Open Source, 1987 (page does not exist)">Open Source, 1987</a>.<a rel="nofollow" class="external autonumber" href="http://spms.masfak.ni.ac.rs/end/papers/55.%20177-HYBRID%20CONTROLLER%20FOR%20SYSTEM%20MANAGEMENT%20OF%20INTEGRATED%20UNIVERSITY.doc">[1]</a></li></ul>
<h2><span class="mw-headline" id="External_links">External links</span><span class="mw-editsection"><span class="mw-editsection-bracket">[</span><a href="/enwiki/w/index.php?title=Bubble_sort&action=edit&section=13" title="Edit section: External links"><span>edit</span></a><span class="mw-editsection-bracket">]</span></span></h2>
<style data-mw-deduplicate="TemplateStyles:r1217611005">.mw-parser-output .side-box{margin:4px 0;box-sizing:border-box;border:1px solid #aaa;font-size:88%;line-height:1.25em;background-color:#f9f9f9;display:flow-root}.mw-parser-output .side-box-abovebelow,.mw-parser-output .side-box-text{padding:0.25em 0.9em}.mw-parser-output .side-box-image{padding:2px 0 2px 0.9em;text-align:center}.mw-parser-output .side-box-imageright{padding:2px 0.9em 2px 0;text-align:center}@media(min-width:500px){.mw-parser-output .side-box-flex{display:flex;align-items:center}.mw-parser-output .side-box-text{flex:1;min-width:0}}@media(min-width:720px){.mw-parser-output .side-box{width:238px}.mw-parser-output .side-box-right{clear:right;float:right;margin-left:1em}.mw-parser-output .side-box-left{margin-right:1em}}</style><div class="side-box side-box-right plainlinks sistersitebox"><style data-mw-deduplicate="TemplateStyles:r1126788409">.mw-parser-output .plainlist ol,.mw-parser-output .plainlist ul{line-height:inherit;list-style:none;margin:0;padding:0}.mw-parser-output .plainlist ol li,.mw-parser-output .plainlist ul li{margin-bottom:0}</style>
<div class="side-box-flex">
<div class="side-box-image"><span class="noviewer" typeof="mw:File"><span><img alt="" src="/upwiki/wikipedia/commons/thumb/d/df/Wikibooks-logo-en-noslogan.svg/40px-Wikibooks-logo-en-noslogan.svg.png" decoding="async" width="40" height="40" class="mw-file-element" srcset="/upwiki/wikipedia/commons/thumb/d/df/Wikibooks-logo-en-noslogan.svg/60px-Wikibooks-logo-en-noslogan.svg.png 1.5x, /upwiki/wikipedia/commons/thumb/d/df/Wikibooks-logo-en-noslogan.svg/80px-Wikibooks-logo-en-noslogan.svg.png 2x" data-file-width="400" data-file-height="400" /></span></span></div>
<div class="side-box-text plainlist">The Wikibook <i><a href="https://en.wikibooks.org/wiki/Algorithm_implementation" class="extiw" title="wikibooks:Algorithm implementation">Algorithm implementation</a></i> has a page on the topic of: <i><b><a href="https://en.wikibooks.org/wiki/Algorithm_implementation/Sorting/Bubble_sort" class="extiw" title="wikibooks:Algorithm implementation/Sorting/Bubble sort">Bubble sort</a></b></i></div></div>
</div>
<link rel="mw-deduplicated-inline-style" href="mw-data:TemplateStyles:r1217611005"><div class="side-box side-box-right plainlinks sistersitebox"><link rel="mw-deduplicated-inline-style" href="mw-data:TemplateStyles:r1126788409">
<div class="side-box-flex">
<div class="side-box-image"><span class="noviewer" typeof="mw:File"><span><img alt="" src="/upwiki/wikipedia/en/thumb/4/4a/Commons-logo.svg/30px-Commons-logo.svg.png" decoding="async" width="30" height="40" class="mw-file-element" srcset="/upwiki/wikipedia/en/thumb/4/4a/Commons-logo.svg/45px-Commons-logo.svg.png 1.5x, /upwiki/wikipedia/en/thumb/4/4a/Commons-logo.svg/59px-Commons-logo.svg.png 2x" data-file-width="1024" data-file-height="1376" /></span></span></div>
<div class="side-box-text plainlist">Wikimedia Commons has media related to <span style="font-weight: bold; font-style: italic;"><a href="https://commons.wikimedia.org/wiki/Category:Bubble_sort" class="extiw" title="commons:Category:Bubble sort">Bubble sort</a></span>.</div></div>
</div>
<link rel="mw-deduplicated-inline-style" href="mw-data:TemplateStyles:r1217611005"><div class="side-box side-box-right plainlinks sistersitebox"><link rel="mw-deduplicated-inline-style" href="mw-data:TemplateStyles:r1126788409">
<div class="side-box-flex">
<div class="side-box-image"><span class="noviewer" typeof="mw:File"><span><img alt="" src="/upwiki/wikipedia/commons/thumb/0/0b/Wikiversity_logo_2017.svg/40px-Wikiversity_logo_2017.svg.png" decoding="async" width="40" height="33" class="mw-file-element" srcset="/upwiki/wikipedia/commons/thumb/0/0b/Wikiversity_logo_2017.svg/60px-Wikiversity_logo_2017.svg.png 1.5x, /upwiki/wikipedia/commons/thumb/0/0b/Wikiversity_logo_2017.svg/80px-Wikiversity_logo_2017.svg.png 2x" data-file-width="626" data-file-height="512" /></span></span></div>
<div class="side-box-text plainlist">Wikiversity has learning resources about <i><b><a href="https://en.wikiversity.org/wiki/Bubble_sort" class="extiw" title="v:Bubble sort">Bubble sort</a></b></i></div></div>
</div>
<ul><li><link rel="mw-deduplicated-inline-style" href="mw-data:TemplateStyles:r1215172403"><cite id="CITEREFMartin2007" class="citation web cs1">Martin, David R. (2007). <a rel="nofollow" class="external text" href="https://web.archive.org/web/20150303084352/http://www.sorting-algorithms.com/bubble-sort">"Animated Sorting Algorithms: Bubble Sort"</a>. Archived from <a rel="nofollow" class="external text" href="http://www.sorting-algorithms.com/bubble-sort">the original</a> on 2015-03-03.</cite><span title="ctx_ver=Z39.88-2004&rft_val_fmt=info%3Aofi%2Ffmt%3Akev%3Amtx%3Abook&rft.genre=unknown&rft.btitle=Animated+Sorting+Algorithms%3A+Bubble+Sort&rft.date=2007&rft.aulast=Martin&rft.aufirst=David+R.&rft_id=http%3A%2F%2Fwww.sorting-algorithms.com%2Fbubble-sort&rfr_id=info%3Asid%2Fen.wikipedia.org%3ABubble+sort" class="Z3988"></span> – graphical demonstration</li>
<li><link rel="mw-deduplicated-inline-style" href="mw-data:TemplateStyles:r1215172403"><cite class="citation web cs1"><a rel="nofollow" class="external text" href="http://lecture.ecc.u-tokyo.ac.jp/~ueda/JavaApplet/BubbleSort.html">"Lafore's Bubble Sort"</a>.</cite><span title="ctx_ver=Z39.88-2004&rft_val_fmt=info%3Aofi%2Ffmt%3Akev%3Amtx%3Abook&rft.genre=unknown&rft.btitle=Lafore%27s+Bubble+Sort&rft_id=http%3A%2F%2Flecture.ecc.u-tokyo.ac.jp%2F~ueda%2FJavaApplet%2FBubbleSort.html&rfr_id=info%3Asid%2Fen.wikipedia.org%3ABubble+sort" class="Z3988"></span> (Java applet animation)</li>
<li><abbr title="On-Line Encyclopedia of Integer Sequences">OEIS</abbr> <a rel="nofollow" class="external text" href="https://oeis.org/A008302">sequence A008302 (Table (statistics) of the number of permutations of [n] that need k pair-swaps during the sorting)</a></li></ul>
<div class="navbox-styles"><style data-mw-deduplicate="TemplateStyles:r1129693374">.mw-parser-output .hlist dl,.mw-parser-output .hlist ol,.mw-parser-output .hlist ul{margin:0;padding:0}.mw-parser-output .hlist dd,.mw-parser-output .hlist dt,.mw-parser-output .hlist li{margin:0;display:inline}.mw-parser-output .hlist.inline,.mw-parser-output .hlist.inline dl,.mw-parser-output .hlist.inline ol,.mw-parser-output .hlist.inline ul,.mw-parser-output .hlist dl dl,.mw-parser-output .hlist dl ol,.mw-parser-output .hlist dl ul,.mw-parser-output .hlist ol dl,.mw-parser-output .hlist ol ol,.mw-parser-output .hlist ol ul,.mw-parser-output .hlist ul dl,.mw-parser-output .hlist ul ol,.mw-parser-output .hlist ul ul{display:inline}.mw-parser-output .hlist .mw-empty-li{display:none}.mw-parser-output .hlist dt::after{content:": "}.mw-parser-output .hlist dd::after,.mw-parser-output .hlist li::after{content:" · ";font-weight:bold}.mw-parser-output .hlist dd:last-child::after,.mw-parser-output .hlist dt:last-child::after,.mw-parser-output .hlist li:last-child::after{content:none}.mw-parser-output .hlist dd dd:first-child::before,.mw-parser-output .hlist dd dt:first-child::before,.mw-parser-output .hlist dd li:first-child::before,.mw-parser-output .hlist dt dd:first-child::before,.mw-parser-output .hlist dt dt:first-child::before,.mw-parser-output .hlist dt li:first-child::before,.mw-parser-output .hlist li dd:first-child::before,.mw-parser-output .hlist li dt:first-child::before,.mw-parser-output .hlist li li:first-child::before{content:" (";font-weight:normal}.mw-parser-output .hlist dd dd:last-child::after,.mw-parser-output .hlist dd dt:last-child::after,.mw-parser-output .hlist dd li:last-child::after,.mw-parser-output .hlist dt dd:last-child::after,.mw-parser-output .hlist dt dt:last-child::after,.mw-parser-output .hlist dt li:last-child::after,.mw-parser-output .hlist li dd:last-child::after,.mw-parser-output .hlist li dt:last-child::after,.mw-parser-output .hlist li li:last-child::after{content:")";font-weight:normal}.mw-parser-output .hlist ol{counter-reset:listitem}.mw-parser-output .hlist ol>li{counter-increment:listitem}.mw-parser-output .hlist ol>li::before{content:" "counter(listitem)"\a0 "}.mw-parser-output .hlist dd ol>li:first-child::before,.mw-parser-output .hlist dt ol>li:first-child::before,.mw-parser-output .hlist li ol>li:first-child::before{content:" ("counter(listitem)"\a0 "}</style><style data-mw-deduplicate="TemplateStyles:r1061467846">.mw-parser-output .navbox{box-sizing:border-box;border:1px solid #a2a9b1;width:100%;clear:both;font-size:88%;text-align:center;padding:1px;margin:1em auto 0}.mw-parser-output .navbox .navbox{margin-top:0}.mw-parser-output .navbox+.navbox,.mw-parser-output .navbox+.navbox-styles+.navbox{margin-top:-1px}.mw-parser-output .navbox-inner,.mw-parser-output .navbox-subgroup{width:100%}.mw-parser-output .navbox-group,.mw-parser-output .navbox-title,.mw-parser-output .navbox-abovebelow{padding:0.25em 1em;line-height:1.5em;text-align:center}.mw-parser-output .navbox-group{white-space:nowrap;text-align:right}.mw-parser-output .navbox,.mw-parser-output .navbox-subgroup{background-color:#fdfdfd}.mw-parser-output .navbox-list{line-height:1.5em;border-color:#fdfdfd}.mw-parser-output .navbox-list-with-group{text-align:left;border-left-width:2px;border-left-style:solid}.mw-parser-output tr+tr>.navbox-abovebelow,.mw-parser-output tr+tr>.navbox-group,.mw-parser-output tr+tr>.navbox-image,.mw-parser-output tr+tr>.navbox-list{border-top:2px solid #fdfdfd}.mw-parser-output .navbox-title{background-color:#ccf}.mw-parser-output .navbox-abovebelow,.mw-parser-output .navbox-group,.mw-parser-output .navbox-subgroup .navbox-title{background-color:#ddf}.mw-parser-output .navbox-subgroup .navbox-group,.mw-parser-output .navbox-subgroup .navbox-abovebelow{background-color:#e6e6ff}.mw-parser-output .navbox-even{background-color:#f7f7f7}.mw-parser-output .navbox-odd{background-color:transparent}.mw-parser-output .navbox .hlist td dl,.mw-parser-output .navbox .hlist td ol,.mw-parser-output .navbox .hlist td ul,.mw-parser-output .navbox td.hlist dl,.mw-parser-output .navbox td.hlist ol,.mw-parser-output .navbox td.hlist ul{padding:0.125em 0}.mw-parser-output .navbox .navbar{display:block;font-size:100%}.mw-parser-output .navbox-title .navbar{float:left;text-align:left;margin-right:0.5em}</style></div><div role="navigation" class="navbox" aria-labelledby="Sorting_algorithms" style="padding:3px"><table class="nowraplinks mw-collapsible autocollapse navbox-inner" style="border-spacing:0;background:transparent;color:inherit"><tbody><tr><th scope="col" class="navbox-title" colspan="2"><link rel="mw-deduplicated-inline-style" href="mw-data:TemplateStyles:r1129693374"><style data-mw-deduplicate="TemplateStyles:r1063604349">.mw-parser-output .navbar{display:inline;font-size:88%;font-weight:normal}.mw-parser-output .navbar-collapse{float:left;text-align:left}.mw-parser-output .navbar-boxtext{word-spacing:0}.mw-parser-output .navbar ul{display:inline-block;white-space:nowrap;line-height:inherit}.mw-parser-output .navbar-brackets::before{margin-right:-0.125em;content:"[ "}.mw-parser-output .navbar-brackets::after{margin-left:-0.125em;content:" ]"}.mw-parser-output .navbar li{word-spacing:-0.125em}.mw-parser-output .navbar a>span,.mw-parser-output .navbar a>abbr{text-decoration:inherit}.mw-parser-output .navbar-mini abbr{font-variant:small-caps;border-bottom:none;text-decoration:none;cursor:inherit}.mw-parser-output .navbar-ct-full{font-size:114%;margin:0 7em}.mw-parser-output .navbar-ct-mini{font-size:114%;margin:0 4em}</style><div class="navbar plainlinks hlist navbar-mini"><ul><li class="nv-view"><a href="/enwiki/wiki/Template:Sorting" title="Template:Sorting"><abbr title="View this template" style=";;background:none transparent;border:none;box-shadow:none;padding:0;">v</abbr></a></li><li class="nv-talk"><a href="/enwiki/wiki/Template_talk:Sorting" title="Template talk:Sorting"><abbr title="Discuss this template" style=";;background:none transparent;border:none;box-shadow:none;padding:0;">t</abbr></a></li><li class="nv-edit"><a href="/enwiki/wiki/Special:EditPage/Template:Sorting" title="Special:EditPage/Template:Sorting"><abbr title="Edit this template" style=";;background:none transparent;border:none;box-shadow:none;padding:0;">e</abbr></a></li></ul></div><div id="Sorting_algorithms" style="font-size:114%;margin:0 4em"><a href="/enwiki/wiki/Sorting_algorithm" title="Sorting algorithm">Sorting algorithms</a></div></th></tr><tr><th scope="row" class="navbox-group" style="width:1%">Theory</th><td class="navbox-list-with-group navbox-list navbox-odd hlist" style="width:100%;padding:0"><div style="padding:0 0.25em">
<ul><li><a href="/enwiki/wiki/Computational_complexity_theory" title="Computational complexity theory">Computational complexity theory</a></li>
<li><a href="/enwiki/wiki/Big_O_notation" title="Big O notation">Big O notation</a></li>
<li><a href="/enwiki/wiki/Total_order" title="Total order">Total order</a></li>
<li><a href="/enwiki/wiki/List_(abstract_data_type)" title="List (abstract data type)">Lists</a></li>
<li><a href="/enwiki/wiki/In-place_algorithm" title="In-place algorithm">Inplacement</a></li>
<li><a href="/enwiki/wiki/Sorting_algorithm#Stability" title="Sorting algorithm">Stability</a></li>
<li><a href="/enwiki/wiki/Comparison_sort" title="Comparison sort">Comparison sort</a></li>
<li><a href="/enwiki/wiki/Adaptive_sort" title="Adaptive sort">Adaptive sort</a></li>
<li><a href="/enwiki/wiki/Sorting_network" title="Sorting network">Sorting network</a></li>
<li><a href="/enwiki/wiki/Integer_sorting" title="Integer sorting">Integer sorting</a></li>
<li><a href="/enwiki/wiki/X_%2B_Y_sorting" title="X + Y sorting">X + Y sorting</a></li>
<li><a href="/enwiki/wiki/Transdichotomous_model" title="Transdichotomous model">Transdichotomous model</a></li>
<li><a href="/enwiki/wiki/Quantum_sort" title="Quantum sort">Quantum sort</a></li></ul>
</div></td></tr><tr><th scope="row" class="navbox-group" style="width:1%">Exchange sorts</th><td class="navbox-list-with-group navbox-list navbox-even hlist" style="width:100%;padding:0"><div style="padding:0 0.25em">
<ul><li><a class="mw-selflink selflink">Bubble sort</a></li>
<li><a href="/enwiki/wiki/Cocktail_shaker_sort" title="Cocktail shaker sort">Cocktail shaker sort</a></li>
<li><a href="/enwiki/wiki/Odd%E2%80%93even_sort" title="Odd–even sort">Odd–even sort</a></li>
<li><a href="/enwiki/wiki/Comb_sort" title="Comb sort">Comb sort</a></li>
<li><a href="/enwiki/wiki/Gnome_sort" title="Gnome sort">Gnome sort</a></li>
<li><a href="/enwiki/wiki/Proportion_extend_sort" title="Proportion extend sort">Proportion extend sort</a></li>
<li><a href="/enwiki/wiki/Quicksort" title="Quicksort">Quicksort</a></li></ul>
</div></td></tr><tr><th scope="row" class="navbox-group" style="width:1%"><a href="/enwiki/wiki/Selection_algorithm" title="Selection algorithm">Selection sorts</a></th><td class="navbox-list-with-group navbox-list navbox-odd hlist" style="width:100%;padding:0"><div style="padding:0 0.25em">
<ul><li><a href="/enwiki/wiki/Selection_sort" title="Selection sort">Selection sort</a></li>
<li><a href="/enwiki/wiki/Heapsort" title="Heapsort">Heapsort</a></li>
<li><a href="/enwiki/wiki/Smoothsort" title="Smoothsort">Smoothsort</a></li>
<li><a href="/enwiki/wiki/Cartesian_tree#Application_in_sorting" title="Cartesian tree">Cartesian tree sort</a></li>
<li><a href="/enwiki/wiki/Tournament_sort" title="Tournament sort">Tournament sort</a></li>
<li><a href="/enwiki/wiki/Cycle_sort" title="Cycle sort">Cycle sort</a></li>
<li><a href="/enwiki/wiki/Weak_heap#Weak-heap_sort" title="Weak heap">Weak-heap sort</a></li></ul>
</div></td></tr><tr><th scope="row" class="navbox-group" style="width:1%">Insertion sorts</th><td class="navbox-list-with-group navbox-list navbox-even hlist" style="width:100%;padding:0"><div style="padding:0 0.25em">
<ul><li><a href="/enwiki/wiki/Insertion_sort" title="Insertion sort">Insertion sort</a></li>
<li><a href="/enwiki/wiki/Shellsort" title="Shellsort">Shellsort</a></li>
<li><a href="/enwiki/wiki/Splaysort" title="Splaysort">Splaysort</a></li>
<li><a href="/enwiki/wiki/Tree_sort" title="Tree sort">Tree sort</a></li>
<li><a href="/enwiki/wiki/Library_sort" title="Library sort">Library sort</a></li>
<li><a href="/enwiki/wiki/Patience_sorting" title="Patience sorting">Patience sorting</a></li></ul>
</div></td></tr><tr><th scope="row" class="navbox-group" style="width:1%">Merge sorts</th><td class="navbox-list-with-group navbox-list navbox-odd hlist" style="width:100%;padding:0"><div style="padding:0 0.25em">
<ul><li><a href="/enwiki/wiki/Merge_sort" title="Merge sort">Merge sort</a></li>
<li><a href="/enwiki/wiki/Cascade_merge_sort" title="Cascade merge sort">Cascade merge sort</a></li>
<li><a href="/enwiki/wiki/Oscillating_merge_sort" title="Oscillating merge sort">Oscillating merge sort</a></li>
<li><a href="/enwiki/wiki/Polyphase_merge_sort" title="Polyphase merge sort">Polyphase merge sort</a></li></ul>
</div></td></tr><tr><th scope="row" class="navbox-group" style="width:1%">Distribution sorts</th><td class="navbox-list-with-group navbox-list navbox-even hlist" style="width:100%;padding:0"><div style="padding:0 0.25em">
<ul><li><a href="/enwiki/wiki/American_flag_sort" title="American flag sort">American flag sort</a></li>
<li><a href="/enwiki/wiki/Bead_sort" title="Bead sort">Bead sort</a></li>
<li><a href="/enwiki/wiki/Bucket_sort" title="Bucket sort">Bucket sort</a></li>
<li><a href="/enwiki/wiki/Burstsort" title="Burstsort">Burstsort</a></li>
<li><a href="/enwiki/wiki/Counting_sort" title="Counting sort">Counting sort</a></li>
<li><a href="/enwiki/wiki/Interpolation_sort" title="Interpolation sort">Interpolation sort</a></li>
<li><a href="/enwiki/wiki/Pigeonhole_sort" title="Pigeonhole sort">Pigeonhole sort</a></li>
<li><a href="/enwiki/wiki/Proxmap_sort" title="Proxmap sort">Proxmap sort</a></li>
<li><a href="/enwiki/wiki/Radix_sort" title="Radix sort">Radix sort</a></li>
<li><a href="/enwiki/wiki/Flashsort" title="Flashsort">Flashsort</a></li></ul>
</div></td></tr><tr><th scope="row" class="navbox-group" style="width:1%">Concurrent sorts</th><td class="navbox-list-with-group navbox-list navbox-odd hlist" style="width:100%;padding:0"><div style="padding:0 0.25em">
<ul><li><a href="/enwiki/wiki/Bitonic_sorter" title="Bitonic sorter">Bitonic sorter</a></li>
<li><a href="/enwiki/wiki/Batcher_odd%E2%80%93even_mergesort" title="Batcher odd–even mergesort">Batcher odd–even mergesort</a></li>
<li><a href="/enwiki/wiki/Pairwise_sorting_network" title="Pairwise sorting network">Pairwise sorting network</a></li>
<li><a href="/enwiki/wiki/Samplesort" title="Samplesort">Samplesort</a></li></ul>
</div></td></tr><tr><th scope="row" class="navbox-group" style="width:1%"><a href="/enwiki/wiki/Hybrid_algorithm" title="Hybrid algorithm">Hybrid sorts</a></th><td class="navbox-list-with-group navbox-list navbox-even hlist" style="width:100%;padding:0"><div style="padding:0 0.25em">
<ul><li><a href="/enwiki/wiki/Block_sort" title="Block sort">Block merge sort</a></li>
<li><a href="/enwiki/wiki/Kirkpatrick%E2%80%93Reisch_sort" title="Kirkpatrick–Reisch sort">Kirkpatrick–Reisch sort</a></li>
<li><a href="/enwiki/wiki/Timsort" title="Timsort">Timsort</a></li>
<li><a href="/enwiki/wiki/Introsort" title="Introsort">Introsort</a></li>
<li><a href="/enwiki/wiki/Spreadsort" title="Spreadsort">Spreadsort</a></li>
<li><a href="/enwiki/wiki/Merge-insertion_sort" title="Merge-insertion sort">Merge-insertion sort</a></li></ul>
</div></td></tr><tr><th scope="row" class="navbox-group" style="width:1%">Other</th><td class="navbox-list-with-group navbox-list navbox-odd hlist" style="width:100%;padding:0"><div style="padding:0 0.25em">
<ul><li><a href="/enwiki/wiki/Topological_sorting" title="Topological sorting">Topological sorting</a>
<ul><li><a href="/enwiki/wiki/Pre-topological_order" title="Pre-topological order">Pre-topological order</a></li></ul></li>
<li><a href="/enwiki/wiki/Pancake_sorting" title="Pancake sorting">Pancake sorting</a></li>
<li><a href="/enwiki/wiki/Spaghetti_sort" title="Spaghetti sort">Spaghetti sort</a></li></ul>
</div></td></tr><tr><th scope="row" class="navbox-group" style="width:1%">Impractical sorts</th><td class="navbox-list-with-group navbox-list navbox-even hlist" style="width:100%;padding:0"><div style="padding:0 0.25em">
<ul><li><a href="/enwiki/wiki/Stooge_sort" title="Stooge sort">Stooge sort</a></li>
<li><a href="/enwiki/wiki/Slowsort" title="Slowsort">Slowsort</a></li>
<li><a href="/enwiki/wiki/Bogosort" title="Bogosort">Bogosort</a></li></ul>
</div></td></tr></tbody></table></div></div>' |
Whether or not the change was made through a Tor exit node (tor_exit_node ) | false |
Unix timestamp of change (timestamp ) | '1714945555' |