Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/sorting/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python气泡排序_Python_Sorting_Bubble Sort - Fatal编程技术网

Python气泡排序

Python气泡排序,python,sorting,bubble-sort,Python,Sorting,Bubble Sort,嘿,代码工作得很好,非常感谢 我还有一个问题。 我想在两个Coulmn之间显示一个箭头。我创建了这段代码,但我真的不知道如何让它进入正在切换的列之间。有什么建议吗 def arrow(lst, i): # function for the arrow if (lst[i], lst[i+1] == lst[i+1], lst[i]): t.home() t.penup() # im thinking som

嘿,代码工作得很好,非常感谢

我还有一个问题。 我想在两个Coulmn之间显示一个箭头。我创建了这段代码,但我真的不知道如何让它进入正在切换的列之间。有什么建议吗

def arrow(lst, i):                 # function for the arrow
if (lst[i], lst[i+1] == lst[i+1], lst[i]):
    t.home()
    t.penup()
                     # im thinking something goes here but i dont know what :P
    t.pendown()
    t.pencolor("red")
    t.right(90)
    t.forward(20)
任何帮助都将不胜感激!非常感谢。
顺便说一句,代码的其余部分类似于imran的代码!:)谢谢大家!

您的代码看起来很像冒泡排序的一个版本。您的版本无法工作的主要问题是,您正在将索引i处的lst与i-1进行比较,当i=0时,i-1会失败。将该部分改为:

        if (lst[i] < lst[i + 1]):
            swapped = False
            lst[i+1], lst[i] = lst[i], lst[i+1]

我根据您的代码编写了一个冒泡排序:

import types

def bubble_sort(lst):
    assert(type(lst)==types.ListType)
    for index in range(1,len(lst)):
        while index > 0 and lst[index-1] > lst[index]:
            lst[index-1] , lst[index] = lst[index] , lst[index-1]
            index -= 1
    return

lst = input("Enter list to be sorted: ")
print "Original: ",lst
bubble_sort(lst)
print "Sorted: ",lst
测试结果如下所示:

C:\Users\NAME\Desktop>bubble.py
Enter list to be sorted: [4, 24, 25, 2, 6, -1, 73, 1]
Original:  [4, 24, 25, 2, 6, -1, 73, 1]
Sorted:  [-1, 1, 2, 4, 6, 24, 25, 73]

希望有帮助

从原始代码中只需编辑一些内容,最好有两个for循环来检查这些值。同样是在你有
[i-1]
之前,它违背了气泡排序的目的,因为你是从左到右排序的,如果这样做有意义的话。无论如何,这就是我所做的

def swap(lst):
    for i in range (len(lst)):
        for j in range (len(lst)-1):
            if lst[j] > lst[j+1]:
                lst[j], lst[j+1] = lst[j+1], lst[j]
                print (lst)


lst = input("Enter list to be sorted: ")
print (lst)
swap(lst)

与您的问题无关,但您的
交换的
变量具有错误的含义(交换时将其设置为false)。应该考虑取消所有使用。您对“已交换”的定义似乎与规范不同。而且您的函数名不好。这行中的
n
是什么:
对于范围(n)内的i
?有人能帮我吗?还有一个问题,您知道如何在每次交换的列表索引下创建箭头吗?喜欢它应该表明哪一个被交换:)@SunShine我认为你不应该像这样更新原始问题。对于不经意的观察者来说,其他人给出的答案对于新问题来说毫无意义。你应该投票,选择一个答案,然后结束这个问题。然后,你应该用你遇到的新问题创建一个新问题,用一个你正在尝试做和已经尝试过的最简单的例子。
def swap(lst):
    for i in range (len(lst)):
        for j in range (len(lst)-1):
            if lst[j] > lst[j+1]:
                lst[j], lst[j+1] = lst[j+1], lst[j]
                print (lst)


lst = input("Enter list to be sorted: ")
print (lst)
swap(lst)