【发布时间】:2016-07-22 18:22:16
【问题描述】:
我正在尝试对从第二个数字开始的数组进行排序,并查看它之前的数字以查看前一个数字是否更大。如果是,我想交换数字,否则将数字保留在原处。目前我的代码没有这样做。当我在下面输入数组时,唯一改变的是 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(a, N) 时,我得到这个输出 [7, 3, 11, 11, 6, 16]。
【问题讨论】:
标签: python arrays sorting if-statement for-loop