Bubblesort算法产生预期结果

时间:2019-02-06 19:28:36

标签: python python-3.x

如果我对这个主题不太了解,请原谅我。 我正在实现一个基本的(在youtube上找到)气泡排序算法。与示例“ list = [3、4、5、9、0、2、1]”相反,我决定尝试实现不同的数字,并从我所了解的角度得到了一个有组织但未排序的列表。我对输出并不感到不满意,我只是好奇其他人对我的不同结果要说些什么,并可能对此有所了解。

这是在Windows计算机上的Visual-studio上使用python。

原始代码是:

df['GEO.id2'] = pd.to_numeric(df['GEO.id2'], errors = 'ignore') # values that can't be converted to integer types will be left alone

这就是我改变以探索结果的方式:

  def bubblesort(list):
      print("bubblesort")

      for k in range(0,len(list)-1, 1):
          for i in range(0,len(list)-1,1):
              if list [i] > list[i + 1]:
                  temp = list[i]
                  list[i] = list[i + 1]
                  list[i + 1] = temp
  list = [43, 7, 30, 234, 35, 77, 79, 45, 34, 21, 26]
  print(list)
  bubblesort(list)
  print(list)

  outputs:
  [43, 7, 30, 234, 35, 77, 79, 45, 34, 21, 26]
  bubblesort
  [7, 21, 26, 30, 34, 35, 43, 45, 77, 79, 234]

很抱歉我的数字是随机的,我搞砸了一些,看它是否会排序相同(而且确实完全一样)。它将某些数字排列在列中,这很酷,但是我希望它们按照上面的值的顺序排序,甚至包括我之后添加的不同数字。 因此,基本上我期望与此类似:

 def bubblesort():
    for i in range(0, len(list)-1, 1):
            if list[i] > list[i + 1]:
                list[i] = list[i + 1]



list = [10,110,13,00,0,110]
list = [10,00,11,00,0,1111]
list = [10,101,00,10,0,110]

print(list)
print(list)
print(list)

实际输出为:

[0,00,10,13,110,110]
[0,00,00,10,11,1111]
[0,00,10,10,101,110]

1 个答案:

答案 0 :(得分:1)

这样做

list = [10,110,13,00,0,110]
list = [10,00,11,00,0,1111]
list = [10,101,00,10,0,110]

您在每一行中为list分配了新内容,因此该代码实际上等效于

list = [10,101,00,10,0,110]

我会将代码更改为以下形式:

def bubblesort(lst):
    for i in range(len(lst)-1):
        if lst[i] > lst[i + 1]:
            lst[i] = lst[i + 1]

lst1 = [10,110,13,00,0,110]
lst2 = [10,00,11,00,0,1111]
lst3 = [10,101,00,10,0,110]

bubblesort(lst1)
bubblesort(lst2)
bubblesort(lst3)

print(lst1) #output: [10, 13, 0, 0, 0, 110]
print(lst2) #output: [0, 0, 0, 0, 0, 1111]
print(lst3) #output: [10, 0, 0, 0, 0, 110]

请注意,我为lst添加了bubblesort参数,因此它不仅可以用于具有固定名称的一个变量。请避免使用list作为Python语言的变量名,因为已经内置了list函数。

请注意,bubblesort函数不是正确的排序实现,尽管由于我很想确切地进行操作,我还是将其保留了。