Created
October 23, 2020 15:54
-
-
Save jjfiv/d964ab65000310d647e07dd3c32f8370 to your computer and use it in GitHub Desktop.
Bubble Sort (Lab 7Opt)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def swap(xs, i, j): | |
""" | |
Proj. 5: | |
Given the list xs, swap elements i and j. | |
Modify xs; don't return anything. | |
""" | |
tmp = xs[i] | |
xs[i] = xs[j] | |
xs[j] = tmp | |
swap_ex = [1,2,3,4] | |
swap(swap_ex, 0, 2) | |
assert(swap_ex == [3,2,1,4]) | |
def is_sorted(xs): | |
""" | |
Proj. 5: | |
Given a list, return true if it's sorted (no out of order pairs); and False otherwise. | |
""" | |
for i in range(len(xs)-1): | |
if xs[i] > xs[i+1]: | |
return False | |
return True | |
def swap_out_of_order(xs): | |
""" | |
This is a lot like ``is_sorted`` but instead of complaining, | |
we call swap to fix any problems we find! | |
Modify xs; don't return anything. | |
""" | |
pass | |
swap_ooo = [4,3,2,1] | |
swap_out_of_order(swap_ooo) | |
assert(swap_ooo == [3,2,1,4]) | |
swap_ooo2 = [1,3,2,4] | |
swap_out_of_order(swap_ooo2) | |
assert(swap_ooo2 == [1,2,3,4]) | |
def bubble_sort(xs): | |
""" | |
To fix up a unsorted list: | |
While it's not sorted, call swap_out_of_order! | |
Modify xs; don't return anything. | |
""" | |
pass | |
shuffled = [7,6,5,4,3,2,1] | |
bubble_sort(shuffled) | |
print(shuffled) | |
assert(is_sorted(shuffled)) | |
assert(shuffled == [1,2,3,4,5,6,7]) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment