This is a Python program to implement bubble sort.
The program sorts a list by bubble sort.
1. Create a function bubble_sort that takes a list as argument.
2. Inside the function create a loop with a loop variable i that counts from the length of the list – 1 to 1.
3. Create an inner loop with a loop variable that counts from 0 up to i – 1.
4. Inside the inner loop, if the elements at indexes j and j + 1 are out of order, then swap them.
5. If in one iteration of the inner loop there were no swaps, then the list is sorted and one can return prematurely.
Here is the source code of a Python program to implement bubble sort. The program output is shown below.
def bubble_sort(alist): for i in range(len(alist) - 1, 0, -1): no_swap = True for j in range(0, i): if alist[j + 1] < alist[j]: alist[j], alist[j + 1] = alist[j + 1], alist[j] no_swap = False if no_swap: return alist = input('Enter the list of numbers: ').split() alist = [int(x) for x in alist] bubble_sort(alist) print('Sorted list: ', end='') print(alist)
1. The user is prompted to enter a list of numbers.
2. The list is passed to the bubble_sort function.
3. The sorted list is displayed.
Case 1: Enter the list of numbers: 4 2 38 10 5 Sorted list: [2, 4, 5, 10, 38] Case 2: Enter the list of numbers: 5 4 3 2 1 Sorted list: [1, 2, 3, 4, 5] Case 3: Enter the list of numbers: 7 3 1 -5 2 10 Sorted list: [-5, 1, 2, 3, 7, 10]
Sanfoundry Global Education & Learning Series – Python Programs.
To practice all Python programs, here is complete set of 150+ Python Problems and Solutions.