Bubble sort in Python
It is one of the simplest sorting techniques where it traverses the whole list by comparing adjacent elements and swapping to move the biggest element to the end one at a time.
eg. list. [4,2,9,1,7,6]
after step 1 [2,4,1,7,6,9]
after step 2 [2,1,4,6,7,9]
after step 3 [1,2,4,6,7,9]
after step 4 [1,2,4,6,7,9]
after step 5 [1,2,4,6,7,9]
CODE:
l1=list()
n=int(input("Enter the number of elements in list: "))
for e in range(n):
ele=int(input("Enter value for element: "))
l1.append(ele)
print("Original list :",l1)
for i in range (1,n):
#in the outer loop it will traverse through each index from 1 till the last
for j in range(0,n-i):
if l1[j]>l1[j+1]:
l1[j+1],l1[j]=l1[j],l1[j+1]
# if current element is bigger than the following element
# then their positions will be swapped
print(f"changing place of {l1[j+1]} and {l1[j]}: ")
print(l1)
print(f"{i} biggest elements have reached the right end i.e. {l1[n-i:]} ")
print("Final sorted list: ")
print(l1)
NOTE: All the print statements are just for explanation purposes and do not contribute in sorting.
OUTPUT (with above example as values):
ALTERNATE CODE WHICH PRINT PASS/STEPS ALSO:
l1=list()
n=int(input("Enter the number of elements in list: "))
for e in range(n):
ele=int(input("Enter value for element: "))
l1.append(ele)
print("Original list :",l1)
for i in range (1,n):
print(f"Pass {i}:")
#in the outer loop it will traverse through each index from 1 till the last
for j in range(0,n-i):
if l1[j]>l1[j+1]:
l1[j+1],l1[j]=l1[j],l1[j+1]
print(f"{l1} : Swapping {l1[j+1]} with {l1[j]}")
continue
print(f"{l1} : No swapping between {l1[j+1]} and {l1[j]}")
# if current element is bigger than the following element
# then their positions will be swapped
print("Final sorted list: ")
print(l1)
Comments
Post a Comment
For any queries or suggestions
Comment Here