我想排序从第二个数字开始的数组,并查看它之前的数组,看看前面的数字是否更大。如果是这样,我想交换数字,否则将数字保持在原来的位置。目前我的代码没有这样做。当我输入下面的数组时,唯一变化的是2变成11,给我两个11在中间。出了什么问题?蟒蛇交换排序没有给出正确的输出
#given an array of digits a of length N
a = [7, 3, 11, 2, 6, 16]
N = len(a)
# moving forward along a starting from the second position to the end
# define _sillysort(a, start_pos):
# set position = start_pos
# moving backwards along a from start_pos:
# if the a[position-1] is greater than a[position]:
# swap a[position-1] and a[position]
def sillysort(a, start_pos):
a_sorted = []
start_pos = a[1]
for position in a:
if a[start_pos-1] >= a[start_pos]:
a[start_pos-1], a[start_pos] = a[start_pos], a[start_pos-1]
else:
a[start_pos-1] = a[start_pos]
a_sorted.append(position)
position += 1
return a_sorted
当运行此,sillysort(一,N),I得到这个输出[7,3,11,11,6,16]。