Skip to content

Instantly share code, notes, and snippets.

@lopezm1
Last active May 20, 2018 21:48
Show Gist options
  • Save lopezm1/c39346503deb6b4b7972c6f45d9c88ff to your computer and use it in GitHub Desktop.
Save lopezm1/c39346503deb6b4b7972c6f45d9c88ff to your computer and use it in GitHub Desktop.
bubblesort
# 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)
@lopezm1
Copy link
Author

lopezm1 commented May 19, 2018

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]

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment