我需要在每个内循环之后存储数组的图像,以便稍后可以在其他地方处理它.

def bubbleSort(arr):
    sort_list = [[]]
    n = len(arr)
    # optimize code, so if the array is already sorted, it doesn't need
    # to go through the entire process
    swapped = False
    print(arr)
    # Traverse through all array elements
    for i in range(n - 1):
        # range(n) also work but outer loop will
        # repeat one time more than needed.
        # Last i elements are already in place
        for j in range(0, n - i - 1):
            sort_list.append(arr)
            # traverse the array from 0 to n-i-1
            # Swap if the element found is greater
            # than the next element
            if arr[j] > arr[j + 1]:
                swapped = True
                arr[j], arr[j + 1] = arr[j + 1], arr[j]

        if not swapped:
            # if we haven't needed to make a single swap, we
            # can just exit the main loop.
            return
    print("sorted arr", sort_list)
    
arr = [2,1,5,7,3]        
bubbleSort(arr)

我得到的输出是:

[2,1,5,7,3] Sorted arr[],[1,2,3,5,7],[1,2,3,5,7],[1,2,3,5,7],[1,2,3,5,7], [1,2,3,5,7],[1,2,3,5,7],[1,2,3,5,7],[1,2,3,5,7],[1,2,3,5,7], [1,2,3,5,7]]

我有一种感觉,我正在做一件愚蠢的事情,但其中的逻辑似乎如此明显,以至于我无法想象为什么它不起作用.

推荐答案

这个管用吗?

def bubbleSort(arr):
    sort_list = []
    n = len(arr)
    # optimize code, so if the array is already sorted, it doesn't need
    # to go through the entire process
    swapped = False
    print(arr)
    # Traverse through all array elements
    for i in range(n - 1):
        # range(n) also work but outer loop will
        # repeat one time more than needed.
        # Last i elements are already in place
        for j in range(0, n - i - 1):
            # traverse the array from 0 to n-i-1
            # Swap if the element found is greater
            # than the next element
            if arr[j] > arr[j + 1]:
                swapped = True
                arr[j], arr[j + 1] = arr[j + 1], arr[j]
        sort_list.append(arr.copy())
        if not swapped:
            # if we haven't needed to make a single swap, we
            # can just exit the main loop.
            return
    print("sorted arr", sort_list)
    
arr = [7,5,3,2,1]        
bubbleSort(arr)

-你在做什么?

[[5, 3, 2, 1, 7], [3, 2, 1, 5, 7], [2, 1, 3, 5, 7], [1, 2, 3, 5, 7]]

Python相关问答推荐

Plotly Dash函数来切换图形参数-pPython

在Python中添加期货之间的延迟

使用Curses for Python保存和恢复终端窗口内容

Polars -转换为PL后无法计算熵.列表

pandas DataFrame中类型转换混乱

使用Python Cerberus初始化一个循环数据 struct (例如树)(v1.3.5)

Image Font生成带有条形码Code 128的条形码时出现枕头错误OSErsor:无法打开资源

Python中的函数中是否有充分的理由接受float而不接受int?

如何在Windows上用Python提取名称中带有逗号的文件?

如何获取TFIDF Transformer中的值?

PMMLPipeline._ fit()需要2到3个位置参数,但给出了4个位置参数

加速Python循环

如何在Django基于类的视图中有效地使用UTE和RST HTIP方法?

如何使用它?

ODE集成中如何终止solve_ivp的无限运行

如何使用pytest来查看Python中是否存在class attribution属性?

从spaCy的句子中提取日期

让函数调用方程

我的字符串搜索算法的平均时间复杂度和最坏时间复杂度是多少?

为什么\b在这个正则表达式中不解释为反斜杠