How to write a Python code for bubble sort algorithm?

Here is an example of Python code using the bubble sort algorithm for sorting.

def bubble_sort(arr):
    n = len(arr)
    
    # 遍历所有数组元素
    for i in range(n):
        
        # 最后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]
    
    return arr

# 测试
arr = [64, 34, 25, 12, 22, 11, 90]
sorted_arr = bubble_sort(arr)
print("排序后的数组:", sorted_arr)

The bubble_sort function in this code implements the bubble sort algorithm. The basic idea of the algorithm is to find the largest (or smallest) element in the unsorted portion each time and swap it to its correct position. This process is repeated multiple times until all elements are in their correct positions, completing the sorting process.

In the main program, we test using a sample array and print the sorted array. The output is: Sorted array: [11, 12, 22, 25, 34, 64, 90]

bannerAds