python交换排序未给出正确的输出
我试图对一个数组进行排序,它从第二个数字开始,然后查看它前面的数字,看看前面的数字是否更大。如果是,我想交换号码,否则就把号码保留在原来的位置。目前我的代码没有这样做。当我输入下面的数组时,唯一变化的是2变成11,中间给了我11个。出什么事了python交换排序未给出正确的输出,python,arrays,sorting,if-statement,for-loop,Python,Arrays,Sorting,If Statement,For Loop,我试图对一个数组进行排序,它从第二个数字开始,然后查看它前面的数字,看看前面的数字是否更大。如果是,我想交换号码,否则就把号码保留在原来的位置。目前我的代码没有这样做。当我输入下面的数组时,唯一变化的是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 p
#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]。您的代码有几个问题
start\u pos=a[1]
如果已经将start_pos作为参数提供给函数,为什么要在函数中重新初始化它。此外,如果a
是要排序的数组,为什么算法的start\u pos
是数组a
本身的第二个元素
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
for in
循环将迭代数组a
,position
将获取数组元素的值。在您的示例中,位置
将按以下顺序取值:
7,3,11,2,6,16
我不明白的是,为什么在for循环的末尾将位置增加1。再一次,您使用数组中的值来索引数组,而不是索引本身
因为在您的示例中,start\u pos
将取值a[1]
即3,您的代码将a[3]和a[2]即2和11进行比较,并进入else条件,使a[3]=a[2],因此在2的位置得到11
您可能对变量名感到困惑。看看这是否对您有帮助。您的代码有几个问题
start\u pos=a[1]
如果已经将start_pos作为参数提供给函数,为什么要在函数中重新初始化它。此外,如果a
是要排序的数组,为什么算法的start\u pos
是数组a
本身的第二个元素
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
for in
循环将迭代数组a
,position
将获取数组元素的值。在您的示例中,位置
将按以下顺序取值:
7,3,11,2,6,16
我不明白的是,为什么在for循环的末尾将位置增加1。再一次,您使用数组中的值来索引数组,而不是索引本身
因为在您的示例中,start\u pos
将取值a[1]
即3,您的代码将a[3]和a[2]即2和11进行比较,并进入else条件,使a[3]=a[2],因此在2的位置得到11
您可能对变量名感到困惑。看看这是否对你有帮助