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]}: ") ...
Comments
Post a Comment
For any queries or suggestions
Comment Here