Python 3中的Bubble Sort

huwehgph  于 2023-11-20  发布在  Python
关注(0)|答案(7)|浏览(147)

用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

vvppvyoh

vvppvyoh1#

每次浏览列表时,你都假设列表是排序的。
然后你重新检查列表中的每一对,如果这对的顺序不正确,就把它们交换掉。
因为这个错误的对:“整个列表仍然不能排序,对吗?”(再次假设)(3)
因此,你必须重复,直到在某个点上if条件不满足。那么这一定意味着它们都是正确的顺序。你停止(并打印)。

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))

字符串
结论:有些编程人员喜欢假设。

btqmn9zl

btqmn9zl2#

关于文本格式-将','替换为', '(添加空格)。
关于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)

字符串

2wnc66cl

2wnc66cl3#

首先,它确实需要7,因为最后一遍没有swap(这是它知道它完成的时候)。将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)

字符串

5lhxktic

5lhxktic4#

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

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]

字符串

gdx19jrr

gdx19jrr5#

这就是解决方案:

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("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)

字符串
为了不再次排序已经排序的列表,并且不添加+1到传递,您必须添加这一行:

if swapped:
            passes += 1
            print('Pass', passes, ':' , ','.join(map(str, mylist)))


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

disbfnqx

disbfnqx6#

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)

字符串

zbq4xfa0

zbq4xfa07#

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

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

字符串

相关问题