Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # Sorts a list using bubble sort.
- def bubble_sort(lst):
- # TODO your code here
- is_sorted = False
- iterations=0
- new_lst=[]
- for elt in lst:
- new_lst.append(elt)
- while is_sorted==False:
- nswaps = 0 ## Number of swaps made
- for i in range (len(new_lst)-1):
- if new_lst[i]>new_lst[i+1]:
- a=new_lst[i]
- new_lst[i]=new_lst[i+1]
- new_lst[i+1]=a
- nswaps+=1
- iterations+=1
- if nswaps==0:
- is_sorted=True
- print(iterations)
- return(new_lst)
- from test import testEqual
- testEqual(bubble_sort([0]), [0]) # Sorts a single element, returns same list
- testEqual(bubble_sort([1, 2, 3, 4, 5]), [1, 2, 3, 4, 5]) # Sorted list is the same
- testEqual(bubble_sort([5, 4, 3, 2, 1]), [1, 2, 3, 4, 5])
- testEqual(bubble_sort([4, 5, 3, 1, 2]), [1, 2, 3, 4, 5])
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement