因此,对于我的作业,我需要创建函数bubblesort
,该函数会冒泡对数字列表进行排序,并在每次通过后返回字典,其中包含数字列表的状态,然后返回排序后的列表。即使我在同一行中打印出值,我似乎也无法使字典正常工作。
附带的是带有doctests的代码
def bubbleSort(numList):
'''
Takes a list and returns 2 values
1st returned value: a dictionary with the state of the list after each complete pass of bubble sort
2nd returned value: the sorted list
>>> bubbleSort([9,3,5,4,1,67,78])
({1: [3, 5, 4, 1, 9, 67, 78], 2: [3, 4, 1, 5, 9, 67, 78], 3: [3, 1, 4, 5, 9, 67, 78], 4: [1, 3, 4, 5, 9, 67, 78], 5: [1, 3, 4, 5, 9, 67, 78]}, [1, 3, 4, 5, 9, 67, 78])
'''
# initialization of dictionary and loop counter
bubble_dict = {}
num_loop = 0
# for loop that resets swapped to False and adds 1 to num_loop
for i in range(len(numList) - 1):
swapped = False
num_loop += 1
# runs through the list index, swaps index with index+1 if appropriate
for j in range(len(numList) - 1):
if numList[j] > numList[j+1]:
temp = numList[j]
numList[j] = numList[j+1]
numList[j+1] = temp
swapped = True
# Everything works up to adding to the dictionary, even printouts
# of num_loop and numList
print(num_loop, numList)
bubble_dict[num_loop] = numList
if not swapped:
break
return bubble_dict, numList