Python bubble sort code implementation

Bubble Sort is also a simple and intuitive sorting algorithm. It has repeatedly visited the sequence to be sorted, comparing two elements at a time, and swapping them if they are in the wrong order. The work of visiting the sequence is repeated until no more exchanges are needed, which means that the sequence has been sorted. The origin of the name of this algorithm is because the smaller the element will slowly "float" to the top of the sequence through exchange. Just as the bubbles of carbon dioxide in carbonated beverages will eventually rise to the top, hence the name "bubble sort".

def bubbleSort(arr):
    n = len(arr)
    
    for i in range(n):
        print(i)
        for j in range(0,n-i-1):

            if arr[j] > arr[j+1]:
                arr[j], arr[j+1] = arr[j+1],arr[j]
                print(arr)

arr = [52,32,43,21,65,98,23]

bubbleSort(arr)

print("排序后得数组:",arr)

Guess you like

Origin blog.csdn.net/weixin_45598506/article/details/113847077