Bubble sort
Bubble sort is a simple sorting algorithm. It works by repeatedly stepping through the list to be sorted, comparing two items at a time, swapping these two items if they are in the wrong order. The pass through the list is repeated until no swaps are needed, which means the list is sorted. The algorithm gets its name from the way smaller elements "bubble" to the top of the list via the swaps.Bubble sort needs O() comparisons to sort items and can sort in-place. Although the algorithm is one of the simplest sorting algorithms to understand and implement, it is too inefficient for use on lists having more than a few elements.
Bubble sort is essentially equivalent in running time to insertion sort -- it compares and swaps the same pairs of elements, but in a different order. Naive implementations of bubble sort (like those below) usually perform badly on already-sorted lists (), while insertion sort needs only operations in this case. Hence most modern algorithm textbooks strongly discourage use of the algorithm, or even avoid mentioning it, in favor of insertion sort. It is possible to reduce the best case complexity to if a flag is used to denote whether any swaps were necessary during the first run of the inner loop. In this case, no swaps would indicate an already sorted list. Also, reversing the order in which the list is traversed for each pass improves the efficiency somewhat. This is sometimes called shuttle sort since the algorithm shuttles from one end of the list to the other.
The bubble sort algorithm is:
- Compare adjacent elements. If the first is greater than the second, swap them.
- Do this for each pair of adjacent elements, starting with the first two and ending with the last two. At this point the last element should be the greatest.
- Repeat the steps for all elements except the last one.
- Keep repeating for one fewer element each time, until you have no more pairs to compare.
| Table of contents |
|
2 See also |
Implementations
Perl
sub bubble_sort(@) {
my @a = @_;
foreach $i (reverse 0..@#a) {
foreach $j (0..$i-1) {
($a[$j],$a[$j+1]) = ($a[$j+1],$a[$j]) if ($a[$j] > $a[$j+1]);
}
}
return @a;
}Python
def bubblesort(iterable):
seq = list(iterable)
for passesLeft in range(len(seq)-1, 0, -1):
for index in range(passesLeft):
if seq[index] > seq[index + 1]:
seq[index], seq[index + 1] = seq[index + 1], seq[index]
return seqSee also