Implementation of Python Bubble Sort

time complexity:

Worst time complexity O(n^2) 
Optimal time complexity O(n): The table traverses once and finds that there are no elements that can be exchanged, and the sorting is over. This is the most ideal 
stability: stable, (no changes before and after execution No change in data, location, etc.)

Ideas:

1. Every time two adjacent elements are compared, if the previous element is larger than the adjacent subsequent element, the position is exchanged

2. After this round, the largest element is placed at the end of the array, and then continue to step 1 to find the second largest element

Code:

def bubble_sort(array):
    """
    冒泡排序:
    每次都是相邻的两个元素比较,谁大就交换位置,
    这样第一轮下来最大的元就放在了最后面,然后再继续下一轮比较找出第二大的元素
    """
    n = len(array)
    for i in range(n):  # 有多少个数就循环多少次
        for j in range(1, n-i):
            if array[j-1] > array[j]:  # 每次都是相邻的两个元素比较
                array[j-1], array[j] = array[j], array[j-1]

    return array


res = bubble_sort(array)  # 冒泡排序
print(res)

Output result:

[1, 2, 3, 4, 5, 6, 7, 8, 9]

Guess you like

Origin blog.csdn.net/qq_37140721/article/details/130317247