Bubble Sort in Python3
Below is an example of the Bubble Sort algorithm in Python3. See the Bubble Sort page for more information and implementations.
bubble-sort in Python3
def bubble_sort():
n = len(array)
while (n > 0):
lastModifiedIndex = 0
currentIndex = 1
while (currentIndex < n):
# if the item at the previous index is greater than the item at the `currentIndex`, swap them
if (array[currentIndex - 1] > array[currentIndex]):
# swap
temp = array[currentIndex - 1]
array[currentIndex - 1] = array[currentIndex]
array[currentIndex] = temp
# save the index that was modified
lastModifiedIndex = currentIndex
currentIndex += 1
# save the last modified index so we know not to iterate past it since all proceeding values are sorted
n = lastModifiedIndex
if __name__ == '__main__':
array = [12, 11, 15, 10, 9, 1, 2, 3, 13, 14, 4, 5, 6, 7, 8]
bubble_sort(array)
print(array)