我想排序從第二個數字開始的數組,並查看它之前的數組,看看前面的數字是否更大。如果是這樣,我想交換數字,否則將數字保持在原來的位置。目前我的代碼沒有這樣做。當我輸入下面的數組時,唯一變化的是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]。