Python Program for Bubble Sort
Intermediate · Searching and sorting
Bubble sort is a simple sorting algorithm that repeatedly compares neighbouring items and swaps them when they are in the wrong order. After each pass through the list, the largest remaining number has bubbled up to the end. This program prints the list after every pass and stops early once a pass makes no swaps.
Program
Original list: [5, 1, 4, 2, 8, 3] After pass 1: [1, 4, 2, 5, 3, 8] After pass 2: [1, 2, 4, 3, 5, 8] After pass 3: [1, 2, 3, 4, 5, 8] After pass 4: [1, 2, 3, 4, 5, 8] No swaps in this pass, so the list is sorted Sorted list: [1, 2, 3, 4, 5, 8]
How it works
- The outer loop runs one pass at a time, and
n - 1passes are always enough. - The inner loop compares each pair
numbers[j]andnumbers[j + 1]and swaps them if the left one is bigger. - Each pass fixes one more number at the end, so the inner loop stops
iplaces earlier every time. swappedrecords whether anything moved: a pass with no swaps means the list is sorted, sobreakends the sort early.- Bubble sort makes about n x n comparisons, so it is used for teaching rather than for large lists.
Another way to write it
Using the built-in sort
Ascending: [1, 2, 3, 4, 5, 8] Descending: [8, 5, 4, 3, 2, 1]
In real programs, use sorted() or list.sort(). Python's built-in sort is much faster than bubble sort on large lists.
Try it yourself
Change the comparison so the list is sorted from largest to smallest.
Edit the program above and press Run, or open it in the full editor to save it and share it. To watch it run line by line, open it in the visualizer.
Related programs
All Python programs · CBSE class 12 practical file · Python exercises