Write A Python Script To Implement Bubble Sort Using List

Given the list containing integers as an input to the python script,  the python script should  sort the list containing numbers using bubble sort in ascending order.

Bubble sort uses comparison of a list item with its next list item.

 

Write A Python Script To Implement Bubble Sort Using List

 

 

Write A Python Script To Implement Bubble Sort Using List

Let's take an integer variable named as length and using the input function call ask your user to enter the list length and then convert it into an integer.

Take an empty list of numbers and use the far look literate from 0 to the least length and accept the user input containing a list of numbers and appended to the empty list.  this will create a list  of numbers into the program.


length = int(input("Enter List Length : "))
numbers = []
for _ in range(length):
   temp = int(input("Enter List Item : "))
   numbers.append(temp)




Take care to loop and iterate from 0 to the list length and get the index,  use another follower to iterate from 0 to length - index - 1  and get the value of next.

Using the if statement check if list[next] is greater than list[next+1] if this is true then swap the list elements.

for index in range(length):
  for next in range(length - index - 1):
      if numbers[next] > numbers[next + 1]:
          numbers[next], numbers[next + 1] = numbers[next + 1], numbers[next]




Once the far look is completed the numbers present in the list will be sorted in ascending order. Use another for loop to iterate all the items present in the list containing numbers and use the print statement to print  numbers present in the list.

for item in numbers:
   print(item, end=" ")





Python Script
================

 
length = int(input("Enter List Length : "))
numbers = []
for _ in range(length):
   temp = int(input("Enter List Item : "))
   numbers.append(temp)


for index in range(length):
  for next in range(length - index - 1):
      if numbers[next] > numbers[next + 1]:
          numbers[next], numbers[next + 1] = numbers[next + 1], numbers[next]


for item in numbers:
   print(item, end=" ")





Output
===============
Enter List Length : 10
Enter List Item : 45
Enter List Item : 23
Enter List Item : 89
Enter List Item : 67
Enter List Item : 62
Enter List Item : 93
Enter List Item : 90
Enter List Item : 53
Enter List Item : 41
Enter List Item : 93
23 41 45 53 62 67 89 90 93 93




Conclusion
=================
Execute the above Python program by providing a list containing numbers as input to the program,  not down the results.

Comment it down below if you have any suggestions to improve the above Python program.






Post a Comment

0 Comments