Skip to content

Instantly share code, notes, and snippets.

@davidejones
Last active September 25, 2016 04:05
Show Gist options
  • Select an option

  • Save davidejones/eda82f2d91b1f4fa7c5885dbf6a7acaf to your computer and use it in GitHub Desktop.

Select an option

Save davidejones/eda82f2d91b1f4fa7c5885dbf6a7acaf to your computer and use it in GitHub Desktop.
first attempt at a bubble sort
def bubble_sort(l):
# keep track of if we did any swapping
swapped = False
# loop over all elements in list
for i in xrange(0, len(l), 1):
# look at this item and the next and see if they need to swap
if i != len(l) - 1:
if l[i] > l[i + 1]:
l[i], l[i + 1] = l[i + 1], l[i]
swapped = True
# if we didn't do any swapping we know we are done, otherwise run another pass
return l if not swapped else bubble_sort(l)
if __name__ == '__main__':
print(bubble_sort([1, 12, 4, 7, 3, 5, 2, 6, 11, 10, 9, 13, 8]))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment