Skip to content

Instantly share code, notes, and snippets.

@ana-balica
Created April 22, 2015 16:59
Show Gist options
  • Save ana-balica/9961a9b7ae7b4ccc26ac to your computer and use it in GitHub Desktop.
Save ana-balica/9961a9b7ae7b4ccc26ac to your computer and use it in GitHub Desktop.
# Bubble Sort Algorithm - sort a sequence in place, for additional convenience
# returns the sequence.
# Time complexity: n^2
# For descending sort change the comparison symbol on line 13:
# if seq[i] > seq[i-1]
# Script is intended to be run with Python3, but is Python2 compatible.
# If running the script with Python2, range() function will return a list.
# Consider changing it to xrange(), if running with Python2.
def bubble_sort(seq):
length = len(seq)
for j in range(length):
for i in range(length-1, j, -1):
if seq[i] < seq[i-1]:
seq[i], seq[i-1] = seq[i-1], seq[i]
return seq
if __name__ == '__main__':
seq = [5, 7, 1, 9, 3, 7, 8]
print(bubble_sort(seq))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment