Bubble sort
Bubble Sort¶
20231214¶
In [ ]:
Copied!
def my_bubble_sort(a_list):
"""
Implementation of the bubble sort algorithm
"""
list_changed = 1
while list_changed != 0:
list_changed = 0
for i in range(len(a_list) - 1):
if a_list[i] > a_list[i + 1]:
##swap if left is bigger than right
a_list[i + 1], a_list[i] = a_list[i], a_list[i + 1]
list_changed += 1
#print(a_list)
return a_list
def bubble_sort(a_list):
"""
Implementation of the bubble sort algorithm
"""
n = len(a_list)
# Traverse through all array elements
for i in range(n):
# Last i elements are already in place, so we don't need to check them
for j in range(0, n-i-1):
# Swap if the element found is greater than the next element
if a_list[j] > a_list[j+1]:
a_list[j], a_list[j+1] = a_list[j+1], a_list[j]
return a_list
def my_bubble_sort(a_list):
"""
Implementation of the bubble sort algorithm
"""
list_changed = 1
while list_changed != 0:
list_changed = 0
for i in range(len(a_list) - 1):
if a_list[i] > a_list[i + 1]:
##swap if left is bigger than right
a_list[i + 1], a_list[i] = a_list[i], a_list[i + 1]
list_changed += 1
#print(a_list)
return a_list
def bubble_sort(a_list):
"""
Implementation of the bubble sort algorithm
"""
n = len(a_list)
# Traverse through all array elements
for i in range(n):
# Last i elements are already in place, so we don't need to check them
for j in range(0, n-i-1):
# Swap if the element found is greater than the next element
if a_list[j] > a_list[j+1]:
a_list[j], a_list[j+1] = a_list[j+1], a_list[j]
return a_list
In [ ]:
Copied!
my_list = [64, 34, 25, 12, 22, 11, 90]
my_bubble_sort(my_list)
my_list = [64, 34, 25, 12, 22, 11, 90]
my_bubble_sort(my_list)
Out[ ]:
[11, 12, 22, 25, 34, 64, 90]
In [ ]:
Copied!
bubble_sort(my_list)
bubble_sort(my_list)
Out[ ]:
[11, 12, 22, 25, 34, 64, 90]
20240110¶
In [1]:
Copied!
def marquins_bubble_sort(a_list: list) -> list:
"""
Marquins implementation of the bubble sort algorithm
20240110
"""
items = len(a_list)
last_index = items - 1
changes = 1
while changes > 0:
changes = 0
for i in range(last_index):
if a_list[i] > a_list[i+1]:
#swap
a_list[i], a_list[i+1] = a_list[i+1], a_list[i]
changes += 1
return a_list
def marquins_bubble_sort(a_list: list) -> list:
"""
Marquins implementation of the bubble sort algorithm
20240110
"""
items = len(a_list)
last_index = items - 1
changes = 1
while changes > 0:
changes = 0
for i in range(last_index):
if a_list[i] > a_list[i+1]:
#swap
a_list[i], a_list[i+1] = a_list[i+1], a_list[i]
changes += 1
return a_list
In [2]:
Copied!
my_list = [1, 5, 6, 2, 4, 8, 7]
marquins_bubble_sort(my_list)
my_list = [1, 5, 6, 2, 4, 8, 7]
marquins_bubble_sort(my_list)
In [3]:
Copied!
marquins_bubble_sort(my_list)
marquins_bubble_sort(my_list)
Out[3]:
[1, 2, 4, 5, 6, 7, 8]