What is Bubble sort?
{{Complex|date=October 2019}} [[File:Bubblesort-edited-color.svg|thumbnail|A bubble sort illustrated]] '''Bubble sort''' is a simple [[sorting algorithm]]. It is simple to understand, so it is usually taught to new students. It is not as efficient as some other sorting algorithms. Bubble sort's name comes from the fact that each item in the list “bubbles” up to where it should go, like [[Liquid Bubble|bubbles]] in [[water]]. ==Algorithm== [[File:Bubble-sort-example-300px.gif|300px|thumb|right|An example of bubble sort. Starting from the beginning of the list, compare the next pair. Swap their positions if they are not in the right order (the second one in the pair is smaller than the first one in the pair). After each [[iteration]], one less element (the last one) is needed to be compared until there are no more elements left to be compared.]] The [[algorithm]] compares pairs of elements in a [[Array data structure|list]]. The elements that make up the pairs are next to each other. Starting at one end of the list, the two elements in each pair are compared to each other in order. That means for example, the first and second element are compared, then the second and third element, and then the third and fourth, and so on. If the elements in the current pair are out of order, then the two elements switch places. This process – of comparing two elements – is done over and over again, until the whole list is sorted. The list is sorted, when there are no more pairs that have to be swapped. In the best case scenario, where the list was already sorted before running the algorithm, the algorithm's complexity is O(n) ([[Big O notation]]). In the worst case, where the list starts off as being sorted in reverse, O(n²). == Implementation == In an imperative programming language, bubble sort can be implemented by using a flag variable and looping through the array's elements: # Set the flag <code>sorted</code>. # Starting at one end, consider every neighbored pair of elements in a vector one after another (in their order)