Skip to content

Instantly share code, notes, and snippets.

@msyvr
Last active December 31, 2024 04:01
Show Gist options
  • Save msyvr/36e0c365ca1fdc68bc58bcd60f0388f6 to your computer and use it in GitHub Desktop.
Save msyvr/36e0c365ca1fdc68bc58bcd60f0388f6 to your computer and use it in GitHub Desktop.
mit 6.0001 - bubble sort
import random
def bubble_sorted_list(ulist):
'''
sort ulist by pairwise checks (aka BUBBLE SORT):
pairwise comparisons from start (index 0) to end (index n),
shifting higher values toward the end
'''
swap = True
while swap:
swap = False
for j in range(len(ulist)-1):
if ulist[j] > ulist[j+1]:
temp = ulist[j]
ulist[j] = ulist[j+1]
ulist[j+1] = temp
swap = True
return(ulist)
if __name__ == "__main__":
ulist = random.sample(range(0, 100), 10)
#s = input('String to sort: ')
#ulist = list(s)
print(f'List to sort: {ulist}')
print(f'Bubble-sorted list: {bubble_sorted_list(ulist)}')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment