如何以气泡排序打印所有过程

2024-06-10 10:58:51 发布

您现在位置:Python中文网/ 问答频道 /正文

有没有什么方法可以让我展示气泡排序的所有过程,就像下图一样

这是我的冒泡排序代码

def bubble_sort(list_a):
    exchanges = True
    i = len(list_a)-1
while i > 0 and exchanges:
    exchanges = False
    for j in range(i):
        if list_a[j]>list_a[j+1]:
            exchanges = True
            list_a[j], list_a[j+1] = list_a[j+1], list_a[j]
    i -= 1


list_a = [70, 60, 50, 40, 30, 20, 10]
bubble_sort(list_a)
print(list_a)

Example output


Tags: and方法代码falsetruelen排序过程
1条回答
网友
1楼 · 发布于 2024-06-10 10:58:51

您可以使用以下代码在每次交换时打印阵列:

def bubble_sort(list_a):
    exchanges = True
    i = len(list_a)-1
    while i > 0 and exchanges:
        exchanges = False
        for j in range(i):
            if list_a[j]>list_a[j+1]:
                exchanges = True
                list_a[j], list_a[j+1] = list_a[j+1], list_a[j]
                #You print the contents of the array after every swap
                print("After pass " + str(i) + ", inner loop "+ str(j) + ": " + str(list_a)) 
        i -= 1

#The following code is only to test the Bubble Sort, so nothing has to be changed here    
list_a = [70, 60, 50, 40, 30, 20, 10]
bubble_sort(list_a)
print(list_a)

或者,您可以在每次通过时使用以下代码打印阵列:

def bubble_sort(list_a):
    exchanges = True
    i = len(list_a)-1
    while i > 0 and exchanges:
        exchanges = False
        for j in range(i):
            if list_a[j]>list_a[j+1]:
                exchanges = True
                list_a[j], list_a[j+1] = list_a[j+1], list_a[j]
        #You print the contents of the array after every pass
        print("After pass " + str(i) + ": " + str(list_a)) 
        i -= 1

#The following code is only to test the Bubble Sort, so nothing has to be changed here    
list_a = [70, 60, 50, 40, 30, 20, 10]
bubble_sort(list_a)
print(list_a)

正如您所看到的,不同之处在于添加print语句的位置

您还可以查看气泡排序的更清晰实现,这可以使整个算法更容易理解:

def bubbleSort(arr): 
    n = len(arr) 
    for i in range(n-1): 
        for j in range(0, n-i-1): 
            if arr[j] > arr[j+1] : 
                arr[j], arr[j+1] = arr[j+1], arr[j]
                #I have included this line so it prints the array at every swap
                print("After pass " + str(i) + ", inner loop "+ str(j) + ": " + str(arr)) 

相关问题 更多 >