【问题标题】:Bubble Sort in Python 3Python 3 中的冒泡排序
【发布时间】:2019-06-20 07:56:06
【问题描述】:

在 Python 3 中编写一个冒泡排序程序。冒泡排序是一种将值列表按顺序排序的算法。

我正试图在最后得到这个结果。

Original List: 4, 9, 74, 0, 9, 8, 28, 1
Sorted List: 0, 1, 4, 8, 9, 9, 28, 74
Number of Passes: 6

我怎样才能完成它?

import sys
def bubblesort(mylist):
        changes = passes = 0
        last = len(mylist)
        swapped = True
        print("Original List: ", ','.join(map(str, mylist)) )
        while swapped:
                swapped = False
                for j in range(1, last):
                        if mylist[j - 1] > mylist[j]:
                                mylist[j], mylist[j - 1] = mylist[j - 1], mylist[j]  # Swap
                                changes += 1
                                swapped = True
                                last = j
                if swapped:
                        passes += 1
                        print('Pass', passes, ':' , ','.join(map(str, mylist)))

        print("\nOriginal List: ", ','.join(map(str, mylist)) )
        print("Sorted List: ", ','.join(map(str, mylist)))
        print("Number of passes =",passes)
        return mylist

print("Welcome to a Bubble Sort Algorithm in Python!")
mylist = " "
while True:
    print("\nBubble sort in Python 3 Program")
    mylist = input("Enter a the value or type Exit to exit: ")
    if (mylist == "exit" or mylist == "Exit" or mylist == "EXIT"):
        print("Goodbye")
        sys.exit()
    else:
        mylist = [int(v) for v in mylist.split(',')]
        bubblesort(mylist)

我得到的输出:

Original List:  4,9,74,0,9,8,28,1
Pass 0 : 4,9,74,0,9,8,28,1
Pass 1 : 4,9,0,9,8,28,1,74
Pass 2 : 4,0,9,8,9,1,28,74
Pass 3 : 0,4,8,9,1,9,28,74
Pass 4 : 0,4,8,1,9,9,28,74
Pass 5 : 0,4,1,8,9,9,28,74
Pass 6 : 0,1,4,8,9,9,28,74


Original List: 0, 1, 4, 8, 9, 9, 28, 74
Sorted List: 0, 1, 4, 8, 9, 9, 28, 74
Number of Passes: 6

我想要的结果:

Original List: 4, 9, 74, 0, 9, 8, 28, 1
Pass 1:  4, 9, 0, 9, 8, 28, 1, 74
Pass 2:  4, 0, 9, 8, 9, 1, 28, 74
Pass 3 : 0, 4, 8, 9, 1, 9, 28, 74
Pass 4 : 0, 4, 8, 1, 9, 9, 28, 74
Pass 5 : 0, 4, 1, 8, 9, 9, 28, 74
Pass 6 : 0, 1, 4, 8, 9, 9, 28, 74

Original List: 4, 9, 74, 0, 9, 8, 28, 1
Sorted List: 0, 1, 4, 8, 9, 9, 28, 74
Number of Passes: 6

【问题讨论】:

    标签: python python-3.x algorithm bubble-sort array-algorithms


    【解决方案1】:

    每次浏览列表时,您都假定列表已排序。 (1)

    然后你迭代列表检查每一对,如果这对不是正确的顺序。交换它们。 (2)

    因为那对不正确:“整个列表还不能排序,对吧?” (再次假设)(3)

    因此,您必须重复,直到某个点没有满足 if 条件。那么这一定意味着它们都按正确的顺序排列。你停下来(并打印)。 (4)

    def bubble(original_list):
        l = original_list.copy() # make a temporary list
        sorted = False  # Assume list is not sorted at first to kick-start the while loop
        count = 0
        while not sorted: 
            sorted = True # (1) Assume that it's sorted
            for i in range(0, len(l) - 1): # (2) len(l)-1 because the last element                                          
                                           # has no thing on the right to compare to.
                if l[i] > l[i + 1]: # (2) check condition
                    sorted = False  # (3) 
                    count += 1
                    l[i], l[i + 1] = l[i + 1], l[i] # (2) swap
    
        print("Original: {}".format(original_list)) # (4)
        print("Sorted: {}".format(l))
        print("Number of swaps: {}".format(count))
    

    结论:一些编程人员喜欢假设。

    【讨论】:

      【解决方案2】:
      def bubblesort(lis):
          num_of_iterations = 0
          for i in range(len(lis)):
              for j in range(i):
                  if lis[j]>lis[j+1]:
                      lis[j], lis[j+1] = lis[j+1], lis[j]
                      num_of_iterations += 1
      
          print(lis,"\n num_of_iterations : ",num_of_iterations)
      
      y =[19,2,31,45,6,11,121,27]
      bubblesort(y)
      

      【讨论】:

      • 欢迎来到 Stack Overflow。虽然这段代码 sn-p 可以解决问题,但 including an explanation 确实有助于提高您的帖子质量。请记住,您是在为将来的读者回答问题,而这些人可能不知道您提出代码建议的原因。
      【解决方案3】:

      使用下面的代码并重复列表中的数字。

      theList = [18, 9, 6, 10]
      currentNumber = theList[0]
      nextNumber = theList[1]
      
      `if` nextNumber < currentNumber:
         toSwap = theList[0]
         theList[0] = theList[1]
         theList[1
                 ] = toSwap
      
      currentNumber = theList[1]
      nextNumber = theList[2]
      

      【讨论】:

        【解决方案4】:

        我相信这是最有效(且易于理解)的冒泡排序方法:

        def bubbleSort(arr):
        n = len(arr)
        
        for i in range(n):  # i : 1 -> n
        
            for j in range(0, n - i - 1):  # j -> n -i -1 , -1 for the j+1 comparison of last element
                if arr[j] > arr[j + 1]:  # if current is bigger than next
                    arr[j], arr[j + 1] = arr[j + 1], arr[j]  # swap current and next
        return arr
        

        【讨论】:

          【解决方案5】:

          首先,它确实需要 7 次,因为最后一遍没有交换(那是它知道完成的时候)。将 passes += 1 和 print 语句移到循环末尾将正确显示这一点。

          对于您想要的输出,围绕循环中的事件顺序进行更改,并添加一个 if 语句来检查更改。 [下面给出]

          对于实际传递的输出(包括最后一个没有变化的传递),只需从下面的代码中删除 if 语句。

          import sys
          
          def bubblesort(mylist):
              changes = passes = 0
              last = len(mylist)
              swapped = True
              print("Original List: ", ','.join(map(str, mylist)) )
              while swapped:
                  swapped = False
          
                  for j in range(1, last):
                      if mylist[j - 1] > mylist[j]:
                          mylist[j], mylist[j - 1] = mylist[j - 1], mylist[j]  # Swap
                          changes += 1
                          swapped = True
                          last = j
          
                  # Only prints and increases number of passes if there was a swap
                  # Remove if statement for the correct number of passes
                  if(swapped):
                    passes += 1
                    print('Pass', passes, ':' , ','.join(map(str, mylist)))
          
              print("Number of passes =",passes)
              return mylist
          
          print("Welcome to a Bubble Sort Algorithm in Python!")
          
          mylist = " "
          while True:
              print("\nBubble sort in Python 3 Program")
              mylist = input("Enter a the value or type Exit to exit: ")
              if (mylist == "exit" or mylist == "Exit" or mylist == "EXIT"):
                  print("Goodbye")
                  sys.exit()
              else:
                  mylist = [int(v) for v in mylist.split(',')]
                  bubblesort(mylist)
          

          【讨论】:

            【解决方案6】:

            这就是解决方案:

            导入系统 def 冒泡排序(mylist): 变化 = 通过 = 0 最后 = len(mylist) 交换=真 print("原始列表:", ','.join(map(str, mylist)) ) 交换时: 交换 = 假 对于范围内的 j(1,最后一个): 如果 mylist[j - 1] > mylist[j]: mylist[j], mylist[j - 1] = mylist[j - 1], mylist[j] # 交换 变化 +=​​ 1 交换=真 最后 = j 如果交换: 通过 += 1 print('Pass', pass, ':' , ','.join(map(str, mylist))) print("通过次数=",passes) 返回我的列表 print("欢迎使用 Python 中的冒泡排序算法!") 我的列表 = " " 而真: print("\nPython 3 程序中的冒泡排序") mylist = input("输入值或输入Exit退出:") if (mylist == "exit" or mylist == "Exit" or mylist == "EXIT"): 打印(“再见”) sys.exit() 别的: mylist = [int(v) for v in mylist.split(',')] 冒泡排序(mylist)

            为了不再对已排序的列表进行排序并且不对通过添加 +1,您必须添加以下行:

            如果交换: 通过 += 1 print('Pass', pass, ':' , ','.join(map(str, mylist)))

            接下来,如果您不想在第一次通过循环后获得原始字母,请将您在循环中显示列表的行放在所有操作之后。

            【讨论】:

              【解决方案7】:

              关于文本格式 - 将 ',' 替换为 ', '(添加一个空格)。

              关于 Pass 0 的打印(甚至在您运行之前) - 将打印调用移动到 passes += 1 之后

              最后 - 在您的示例中,冒泡排序完成的遍数将是 7 到 6 遍,您仍会修改列表,并且您检测到列表的最后一遍已排序。

              修改后的代码如下:

              import sys
              def bubblesort(mylist):
                  changes = passes = 0
                  last = len(mylist)
                  swapped = True
                  print("Original List: ", ', '.join(map(str, mylist)) )
                  while swapped:
                      swapped = False
                      for j in range(1, last):
                          if mylist[j - 1] > mylist[j]:
                              mylist[j], mylist[j - 1] = mylist[j - 1], mylist[j]  # Swap
                              changes += 1
                              swapped = True
                              last = j
                      passes += 1
                      print('Pass', passes, ':', ', '.join(map(str, mylist)))
              
                  print("Number of passes =",passes)
                  return mylist
              
              print("Welcome to a Bubble Sort Algorithm in Python!")
              
              while True:
                  print("\nBubble sort in Python 3 Program")
                  mylist = input("Enter a the value or type Exit to exit: ")
                  if (mylist == "exit" or mylist == "Exit" or mylist == "EXIT"):
                      print("Goodbye")
                      sys.exit()
                  else:
                      mylist = [int(v) for v in mylist.split(',')]
                      bubblesort(mylist)
              

              【讨论】:

                猜你喜欢
                • 1970-01-01
                • 1970-01-01
                • 1970-01-01
                • 1970-01-01
                • 2017-07-29
                • 2017-06-29
                • 1970-01-01
                • 2017-03-19
                • 2018-07-10
                相关资源
                最近更新 更多