问题是为什么变量测试为空?该程序将返回正确排序的数组。但它似乎没有被分配。
def my_sort(array_to_sort):
sort = False
number_of_items = len(array_to_sort)
print "sorted array: ", array_to_sort
for i in range(0, number_of_items-1):
if array_to_sort[i] > array_to_sort[i+1]:
tmp = array_to_sort[i]
array_to_sort[i] = array_to_sort[i+1]
array_to_sort[i+1] = tmp
sort = True
if sort == True:
my_sort(array_to_sort)
elif sort == False:
return array_to_sort
if __name__ == '__main__':
# main()
arr = [4,5,7,3,2,1]
test = my_sort(arr)
print (test)
这将返回以下内容。
sorted array: [4, 5, 7, 3, 2, 1]
sorted array: [4, 5, 3, 2, 1, 7]
sorted array: [4, 3, 2, 1, 5, 7]
sorted array: [3, 2, 1, 4, 5, 7]
sorted array: [2, 1, 3, 4, 5, 7]
sorted array: [1, 2, 3, 4, 5, 7]
None
答案 0 :(得分:5)
你在第一个条件下忘了回来:
if sort == True:
return my_sort(array_to_sort)
您也不需要将布尔值与布尔值进行比较。您的代码应如下所示:
def my_sort(array_to_sort):
sort = False
number_of_items = len(array_to_sort)
print "sorted array: ", array_to_sort
for i in range(0, number_of_items-1):
if array_to_sort[i] > array_to_sort[i+1]:
tmp = array_to_sort[i]
array_to_sort[i] = array_to_sort[i+1]
array_to_sort[i+1] = tmp
sort = True
if sort:
return my_sort(array_to_sort)
else:
return array_to_sort
if __name__ == '__main__':
# main()
arr = [4,5,7,3,2,1]
test = my_sort(arr)
print (test)