Bubble sort
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 bubbles in water.
Algorithm
The algorithm compares pairs of elements in a 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
sorted
. - Starting at one end, consider every neighbored pair of elements in a vector one after another (in their order).
- If a pair's elements are out of order, swap them, and clear the flag
sorted
. - Repeat the previous steps until
sorted
remains set.
Alternatively, since the greatest value ascends to the highest index within the first iteration and then has reached its final right position, two for-loops nested into one another sort the vector, too: <syntaxhighlight lang="pascal"> for top ≔ high(vector)−1 downto low(vector) do
for current ≔ low(vector) to top do if vector[current] > vector[current+1] then exchange(vector, current, current+1)
</syntaxhighlight>
Bubble Sort Media
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.