Advertisement
elena_gancedo

Bubble-sort unsorted list

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