2016-04-03 93 views
1

我想排序从第二个数字开始的数组,并查看它之前的数组,看看前面的数字是否更大。如果是这样,我想交换数字,否则将数字保持在原来的位置。目前我的代码没有这样做。当我输入下面的数组时,唯一变化的是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]。

回答

0

代码有几个问题

start_pos = a[1]

如果您已经提供START_POS作为参数传递给你的函数,你为什么在函数重新初始化它。此外,如果a是要排序的数组,那么为什么您的算法的start_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循环将遍历阵列aposition将采取数组的元素的值。在您的例子position将采取以下顺序值:

7, 3, 11, 2, 6, 16

我不会在的的结束for循环明白的是你为什么要递增位置1。再次,您正在使用数组内的值来索引数组而不是索引本身。由于在你的例子中,start_pos将采用值a[1]即3,你的代码比较一个[3]和一个[2]即2和11,并进入else条件,并使[3] = a [2 ],所以你得到11的位置2

你可能已经弄糊涂了变量名称。看看这是否有助于你。