Advertisement
brendan-stanford

bubble_sort_random

Aug 22nd, 2019
287
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.31 KB | None | 0 0
  1. #This program takes an unsorted list and sorts it, then stores the results in copy_list
  2. from random import randint
  3.  
  4. #my_list becomes filled with a collection of random integers, the amount of which is specified the user;
  5. #individual list items could be specified by replacing randint with another input block
  6. my_list = []
  7. for i in range(int(input("Number of items in unsorted list:"))+1):
  8. my_list.append(randint(0, 10))
  9.  
  10. copy_list = []
  11.  
  12. def bubble_sort(unsorted):
  13. #iterates through original list and copies each item into copy_list
  14. for item in my_list:
  15. copy_list.append(item)
  16.  
  17. #sets loop condition so loop will proceed
  18. swapped = True
  19. while swapped == True:
  20.  
  21. #sets loop to terminate after having iterated and swapped all necessary items in copy list
  22. swapped = False
  23. for num in range(len(copy_list)-1):
  24.  
  25. #swaps item order if a preceding number is greater than that which follows
  26. if copy_list[num] > copy_list[num + 1]:
  27. copy_list[num], copy_list[num + 1] = copy_list[num + 1], copy_list[num]
  28. #sets loop to continue until numbers are ordered
  29. swapped = True
  30.  
  31. #Calls function with input list
  32. bubble_sort(my_list)
  33.  
  34. #prints original list and copied list
  35. print(my_list)
  36. print(copy_list)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement