Last active
May 20, 2018 21:48
-
-
Save lopezm1/c39346503deb6b4b7972c6f45d9c88ff to your computer and use it in GitHub Desktop.
bubblesort
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
# Let's bubblesort | |
def swap(a, b): | |
return b, a | |
def bubblesort(numbers): | |
length = len(numbers) | |
swapped = True | |
while(swapped): | |
swapped = False # break the loop if nothing gets swapped | |
print("iteration -----------") | |
for idx, val in enumerate(numbers[:-1]): | |
print(numbers, idx) | |
print("comparing: ", numbers[idx], numbers[idx+1]) | |
if(numbers[idx] > numbers[idx+1]): | |
print("swapping: ", numbers[idx], numbers[idx+1]) | |
numbers[idx], numbers[idx+1] = swap(numbers[idx], numbers[idx+1]) | |
swapped = True # do another iteration | |
print("Bubblesorted: ", numbers) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
iteration -----------
[5, 1, 4, 2, 8] 0
comparing: 5 1
swapping: 5 1
[1, 5, 4, 2, 8] 1
comparing: 5 4
swapping: 5 4
[1, 4, 5, 2, 8] 2
comparing: 5 2
swapping: 5 2
[1, 4, 2, 5, 8] 3
comparing: 5 8
iteration -----------
[1, 4, 2, 5, 8] 0
comparing: 1 4
[1, 4, 2, 5, 8] 1
comparing: 4 2
swapping: 4 2
[1, 2, 4, 5, 8] 2
comparing: 4 5
[1, 2, 4, 5, 8] 3
comparing: 5 8
iteration -----------
[1, 2, 4, 5, 8] 0
comparing: 1 2
[1, 2, 4, 5, 8] 1
comparing: 2 4
[1, 2, 4, 5, 8] 2
comparing: 4 5
[1, 2, 4, 5, 8] 3
comparing: 5 8
Bubblesorted: [1, 2, 4, 5, 8]