我需要在每个内循环之后存储数组的图像,以便稍后可以在其他地方处理它.
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]]
我有一种感觉,我正在做一件愚蠢的事情,但其中的逻辑似乎如此明显,以至于我无法想象为什么它不起作用.