Advertisement
Guest User

Untitled

a guest
Apr 24th, 2017
58
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.89 KB | None | 0 0
  1. # Sorts a list using bubble sort.
  2. def bubble_sort(lst):
  3. # TODO your code here
  4. is_sorted = False
  5. iterations=0
  6. new_lst=[]
  7. for elt in lst:
  8. new_lst.append(elt)
  9. while is_sorted==False:
  10. nswaps = 0 ## Number of swaps made
  11. for i in range (len(new_lst)-1):
  12. if new_lst[i]>new_lst[i+1]:
  13. a=new_lst[i]
  14. new_lst[i]=new_lst[i+1]
  15. new_lst[i+1]=a
  16. nswaps+=1
  17. iterations+=1
  18. if nswaps==0:
  19. is_sorted=True
  20. print(iterations)
  21. return(new_lst)
  22.  
  23.  
  24.  
  25. from test import testEqual
  26. testEqual(bubble_sort([0]), [0]) # Sorts a single element, returns same list
  27. testEqual(bubble_sort([1, 2, 3, 4, 5]), [1, 2, 3, 4, 5]) # Sorted list is the same
  28. testEqual(bubble_sort([5, 4, 3, 2, 1]), [1, 2, 3, 4, 5])
  29. testEqual(bubble_sort([4, 5, 3, 1, 2]), [1, 2, 3, 4, 5])
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement