Created
July 30, 2019 20:31
-
-
Save douglasrizzo/7c43e376875111fe104c5e640c653185 to your computer and use it in GitHub Desktop.
Bubble sort in Python
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
# This is a simple implementation of bubblesort | |
# which I made during a Python lesson | |
from random import shuffle | |
# size of the list that will ne sorted | |
n = int(input('Size of the input vector: ')) | |
l = list(range(n)) | |
# shuffle list | |
shuffle(l) | |
print('start:', l) | |
changed = True # flag to know when the list has not been changed | |
passes = 0 # count number of passes | |
changes = 0 # count number of changes to the list | |
# repeat until numbers don't swap positions anymore in a pass | |
# after a pass, if no number changes position in the list, it means the algorithm is over | |
while changed: | |
changed = False | |
passes += 1 | |
# iterate through the list | |
for i in range(len(l) - 1): | |
# if the number in the current position is larger than the number in the next position | |
if l[i] > l[i + 1]: | |
changes += 1 | |
# we swap them | |
aux = l[i] | |
l[i] = l[i + 1] | |
l[i + 1] = aux | |
# swaping two numbers means we'll need to make another pass after the current one ends | |
changed = True | |
print(' end:', l) | |
print('passes:', passes) | |
print('changes:', changes) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment