Bubble sort algorithm, python code

Recommendation: Introduction to Top Ten Classic Sorting Algorithms , Introduction to Bubble Sort

Python code implementation:

# 冒泡排序:升序
def bubbleSort(array: list) -> list:
    # i表示循环次数,与下标无关;j表示数组下标
    for i in range(1, len(array)):
        for j in range(0, len(array) - i):
            if array[j] > array[j + 1]:
                temp = array[j]
                array[j] = array[j + 1]
                array[j + 1] = temp
    return array

if __name__ == '__main__':
    array = [2, 4, 1, 6, 3, 5, 3, 6, 9, 2]
    print(bubbleSort(array))     # [1, 2, 2, 3, 3, 4, 5, 6, 6, 9]

Note: You can use the unique variable exchange method in python to realize the exchange of two variables:

a, b = b, a     # a,b变量数值交换

Then the bubble sort code can be simplified as:

# 冒泡排序:升序
def bubbleSort(array: list) -> list:
    # i表示循环次数,与下标无关;j表示数组下标
    for i in range(1, len(array)):
        for j in range(0, len(array) - i):
            if array[j] > array[j + 1]:
                array[j], array[j + 1] = array[j + 1], array[j]
    return array

if __name__ == '__main__':
    array = [2, 4, 1, 6, 3, 5, 3, 6, 9, 2]
    print(bubbleSort(array))    # [1, 2, 2, 3, 3, 4, 5, 6, 6, 9]

In general, bubble sort requires two for loops, so the time complexity is O(n 2 )

But in the best case (that is, the array is already in order), only the size needs to be judged without performing the exchange operation; at this time, we can set a flag variable in the loop to mark whether the exchange operation has been performed; if the first If the exchange operation is not performed during the loop, it means that the array is already in order, and you can jump out of the loop. At this time, only one for loop is needed, and the time complexity is O(n)

So the general time complexity of bubble sort is O(n 2 ), worst case is O(n 2 ), best case is O(n)

Guess you like

Origin blog.csdn.net/qq_43799400/article/details/130877401