Bubble sort, sometimes referred to assinking sort, is a simplesorting algorithm that repeatedly steps through the input list element by element, comparing the current element with the one after it,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 acomparison sort, is named for the way the larger elements "bubble" up to the top of the list.
It performs poorly in real-world use and is used primarily as an educational tool. More efficient algorithms such asquicksort,timsort, ormerge sort are used by the sorting libraries built into popular programming languages such as Python and Java.[2][3]
The earliest description of the bubble sort algorithm was in a 1956 paper by mathematician and actuary Edward Harry Friend,[4]Sorting on electronic computer systems,[5] published in the third issue of the third volume of theJournal 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, includingKenneth E. Iverson who coined its current name.
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 eachiteration, one less element (the last one) is needed to be compared until there are no more elements left to be compared.
Bubble sort has a worst-case and average complexity of, where is the number of items being sorted. Most practical sorting algorithms have substantially better worst-case or average complexity, often. Even other sorting algorithms, such asinsertion sort, generally run faster than bubble sort, and are no more complex. For this reason, bubble sort is rarely used in practice.
Likeinsertion sort, bubble sort isadaptive, which can give it an advantage over algorithms likequicksort. This means that it may outperform those algorithms in cases where the list is already mostly sorted (having a small number ofinversions), despite the fact that it has worse average-case time complexity. For example, bubble sort is on a list that is already sorted, while quicksort would still perform its entire sorting process.
While any sorting algorithm can be made on a presorted list simply by checking the list before the algorithm runs, improved performance on almost-sorted lists is harder to replicate.
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 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 ofThe 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 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 likequicksort.
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 inbold are being compared. Three passes will be required;
First Pass
(51 4 2 8 ) → (15 4 2 8 ), Here, algorithm compares the first two elements, and swaps since 5 > 1.
( 154 2 8 ) → ( 145 2 8 ), Swap since 5 > 4
( 1 452 8 ) → ( 1 425 8 ), Swap since 5 > 2
( 1 4 258 ) → ( 1 4 258 ), Now, since these elements are already in order (8 > 5), algorithm does not swap them.
Second Pass
(14 2 5 8 ) → (14 2 5 8 )
( 142 5 8 ) → ( 124 5 8 ), Swap since 4 > 2
( 1 245 8 ) → ( 1 245 8 )
( 1 2 458 ) → ( 1 2 458 )
Now, the array is already sorted, but the algorithm does not know if it is completed. The algorithm needs one additionalwhole pass withoutany swap to know it is sorted.
Inpseudocode the algorithm can be expressed as (0-based array):
procedurebubbleSort(A:listofsortableitems)n:=length(A)repeatswapped:=falsefori:=1ton-1inclusivedo{ if this pair is out of order }ifA[i-1]>A[i]then{ swap them and remember something changed }swap(A[i-1],A[i])swapped:=trueendifendforuntilnotswappedendprocedure
Comparing A and ASwapping since >Continuing since ≯The list is sorted
0
The bubble sort algorithm can be optimized by observing that then-th pass finds then-th largest element and puts it into its final place. So, the inner loop can avoid looking at the lastn − 1 items when running for then-th time:
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 50% improvement in the worst-case comparison count (though no improvement in swap counts), and adds very little complexity because the new code subsumes theswapped variable:
To accomplish this in pseudocode, the following can be written:
Alternate modifications, such as thecocktail shaker sort attempt to improve on the bubble sort performance while keeping the same idea of repeatedly comparing and swapping adjacent items.
Bubble sort. The list was plotted in a Cartesian coordinate system, with each point (x,y) indicating that the valuey is stored at indexx. 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, itsO(n2) complexity means that its efficiency decreases dramatically on lists of more than a small number of elements. Even among simpleO(n2) sorting algorithms, algorithms likeinsertion 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 introductorycomputer science students. However, some researchers such asOwen 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.[6]
TheJargon File, which famously callsbogosort "the archetypical [sic] perversely awful algorithm", also calls bubble sort "the generic bad algorithm".[7]Donald Knuth, inThe 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.[8]
Bubble sort isasymptotically 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 morebranch mispredictions.[citation needed] Experiments by Astrachan sorting strings inJava show bubble sort to be roughly one-fifth as fast as an insertion sort and 70% as fast as aselection sort.[6]
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 (2n). For example, it is used in a polygon filling algorithm, where bounding lines are sorted by theirx coordinate at a specific scan line (a line parallel to thex axis) and with incrementingy their order changes (two elements are swapped) only at intersections of two lines. Bubble sort is a stable sort algorithm, like insertion sort.
Bubble sort has been occasionally referred to as a "sinking sort".[9]
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 thesifting orsinking technique.[10]
This debate is perpetuated by the ease with which one may consider this algorithm from two different but equally valid perspectives:
Thelarger values might be regarded asheavier and therefore be seen to progressivelysink to thebottom of the list
Thesmaller values might be regarded aslighter and therefore be seen to progressivelybubble up to thetop of the list.
In a 2007 interview, formerGoogle CEOEric Schmidt asked then-presidential candidateBarack Obama about the best way to sort one millionintegers; Obama paused for a moment and replied: "I think the bubble sort would be the wrong way to go."[11][12]
^Donald Knuth.The Art of Computer Programming, Volume 3:Sorting and Searching, Second Edition. Addison-Wesley, 1998.ISBN0-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.)
^Barack Obama, Eric Schmidt (Nov 14, 2007).Barack Obama | Candidates at Google(Video) (YouTube). Mountain View, CA 94043 The Googleplex: Talks at Google. Event occurs at 23:20.Archived from the original on September 7, 2019. RetrievedSep 18, 2019.{{cite AV media}}: CS1 maint: location (link)