# Implementation of Bubble Sort

0 like 0 dislike
353 views

recategorized
Write a program to to implement Bubble Sort

0 like 0 dislike
by Goeduhub's Expert (7.6k points)
edited

## Ques. Write a program to to implement Bubble Sort

Bubble sort : Bubble sort  is a sorting algorithm which  is also called  comparison-based algorithm in which each pair of adjacent elements is compared and the elements are swapped if they are not in order.

Example :

First Pass:
15 ,1 , 4 , 2  , 18   =>  1, 15, 4, 2, 18   # Here, algorithm compares the first two elements, and swaps since 15 > 1.
1 , 15 , 4 , 2  ,18   =>  1, 4 ,15 ,2 ,18  #Swap since 15 > 4
1 , 4 , 15 , 2 , 18   => 1 ,4 ,2 ,15, 18  #Swap since 15 > 2
1 , 4 , 2 , 15 , 18   =>  1, 4 ,2 ,15 ,18   #Now, since these elements are already in order (18 > 15), algorithm does not swap them.

Second Pass:
1 , 4  , 2 ,15 ,18  =>  1 , 4 , 2 ,15 ,18
1 , 4 , 2 , 15 ,18  =>  1 , 2 , 4 ,15 ,18   #Swap since 4 > 2
1 ,2 , 4 , 15 , 18  =>  1 , 2  ,4 ,15 ,18
1 , 2 , 4 ,15  ,18  =>  1 , 2 , 4 ,15 ,18

Now, the array is already sorted, but our algorithm does not know if it is completed. The algorithm needs one whole pass without any swap to know it is sorted.

Third Pass:
1 ,2 ,4 ,15 ,18  =>  1 ,2 ,4 ,15, 18
1 ,2 ,4 ,15 ,18  =>  1 ,2 ,4 ,15 ,18
1 ,2 ,4 ,15 ,18  =>  1 ,2 ,4 ,15, 18
1 ,2 ,4 ,15 ,18  =>  1 ,2 ,4 ,15 ,18

Algorithm :

BS(list)
for all elements of list
if list[i] > list[i+1]
swap(list[i], list[i+1])
end if
end for

return list

end BS

Program :

a1=input("enter elements : ")

a=a1.split(",")

b=[]

for i in range(0,len(a)):

for j in range(i+1,len(a)):

if a[j]<a[i]:

temp = a[j]

a[j]=a[i]

a[i]=temp

print("List of sorted elements : ",end="")

for i in a:

b.append(i)

print(b)

Output :

enter elements : 45,34,23,1,54,2

List of sorted elements: ['1', '2', '23', '34', '45', '54']

## For more Rajasthan Technical University CSE-III Sem DSA Lab Experiments  CLICK HERE

Learn & Improve In-Demand Data Skills Online in this Summer With  These High Quality Courses[Recommended by GOEDUHUB]:-

Best Data Science Online Courses[Lists] on:-

Claim your 10 Days FREE Trial for Pluralsight.