elena_gancedo

Bubble_sort_list_user

Sep 4th, 2019
183
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.44 KB | None | 0 0
  1. print ("******************************************************************")
  2. # The user creates the list by entering the numbers
  3. my_list = []
  4. num = int(input('How many items in the list?: '))
  5. for n in range(num):
  6.     numbers = int(input("Enter a number in the list: "))
  7.     my_list.append(numbers)
  8. # Making a copy of a list
  9. unclassified  = my_list[:]
  10. # Create a function for the bubble sort algorithm.
  11. # With a single parameter, which will be the data to be sorted.  
  12. def bubble_sort(unclassified):
  13. #  Initialise a swapped variable to be True
  14.     changed = True
  15. # Start a loop that runs until swapped is no longer True    
  16.     while changed == True:
  17. #  Change swapped to False      
  18.         changed = False
  19. # Iterate over the unsorted list        
  20.         for item in range(len(unclassified) - 1):
  21. # Compare adjacent items in the list.      
  22.             if unclassified[item] > unclassified[item+1]:
  23.                 unclassified[item], unclassified[item+1] = unclassified[item+1], unclassified[item] # Swapping list items around
  24. # Change swapped back to True if a swap has been made          
  25.                 changed = True
  26. # Return the ordered list, if no swaps have been made after a full iteration.                
  27.     return unclassified
  28. # Print the list    
  29. print(my_list)
  30. bubble_sort(unclassified)
  31. # Print the sorted list
  32. print(unclassified)
  33. print ("******************************************************************")
Advertisement
Add Comment
Please, Sign In to add comment