Bubble Sort
Write a Python program to sort a list of elements using the bubble sort algorithm.
Bubble sort, sometimes referred to as sinking sort, is a simple sorting algorithm that repeatedly steps through the list, compares adjacent elements and swaps them if they are in the wrong order. The pass through the list is repeated until the list is sorted. The algorithm, which is a comparison sort, is named for the way smaller or larger elements "bubble" to the top of the list.
5,3,4,2,1
3,5,4,2,1
3,4,5,2,1
3,4,2,5,1
3,4,2,1,5
3,4,2,1,5
3,2,4,1,5
3,2,1,4,5
2,3,1,4,5
2,1,3,4,5
1,2,3,4,5
def bubble_sort(items):
n = len(items)
for i in range(n-1):
for j in range(n-i-1):
# traverse the list from 0 to n-i-1
# Swap if the element found is greater than the next element
if items[j] > items[j+1] :
items[j], items[j+1] = items[j+1], items[j]
return items
mylist = [5,3,4,2,1]
bubble_sort(mylist)
i and j values for every iteration
i --> 0,1,2,3,4
i = 0 j = 4 --> 0,1,2,3
i = 1 j = 3 --> 0,1,2
i = 2 j = 2 --> 0,1
i = 3 j = 1 --> 0