Created
April 22, 2015 16:59
-
-
Save ana-balica/9961a9b7ae7b4ccc26ac to your computer and use it in GitHub Desktop.
This file contains 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
# 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