Skip to content

Instantly share code, notes, and snippets.

@uuklanger
Created February 10, 2020 17:34
Show Gist options
  • Save uuklanger/a7d8b011b71b4682d822e7e1e83e42ba to your computer and use it in GitHub Desktop.
Save uuklanger/a7d8b011b71b4682d822e7e1e83e42ba to your computer and use it in GitHub Desktop.
HOWTO - Bubble Sort in Python
#!/usr/bin/env python3
#
# https://stackabuse.com/bubble-sort-in-python/
#
def bubble_sort(our_list):
# We go through the list as many times as there are elements
for i in range(len(our_list)):
# We want the last pair of adjacent elements to be (n-2, n-1)
for j in range(len(our_list) - 1):
if our_list[j] > our_list[j+1]:
# Swap
our_list[j], our_list[j+1] = our_list[j+1], our_list[j]
def bubble_sort_optimized(our_list):
# We want to stop passing through the list
# as soon as we pass through without swapping any elements
has_swapped = True
while(has_swapped):
has_swapped = False
for i in range(len(our_list) - 1):
if our_list[i] > our_list[i+1]:
# Swap
our_list[i], our_list[i+1] = our_list[i+1], our_list[i]
has_swapped = True
def bubble_sort_optimized_boolean(our_list):
has_swapped = True
num_of_iterations = 0
while(has_swapped):
has_swapped = False
for i in range(len(our_list) - num_of_iterations - 1):
if our_list[i] > our_list[i+1]:
# Swap
our_list[i], our_list[i+1] = our_list[i+1], our_list[i]
has_swapped = True
num_of_iterations += 1
#
# Run
# OUTPUT [2, 6, 8, 13, 18, 19]
#
our_list = [19, 13, 6, 2, 18, 8]
bubble_sort(our_list)
print(our_list)
our_list = [19, 13, 6, 2, 18, 8]
bubble_sort_optimized(our_list)
print(our_list)
our_list = [19, 13, 6, 2, 18, 8]
bubble_sort_optimized_boolean(our_list)
print(our_list)
#
# end of script
#
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment