Python 从给定的列表中订购一个数字列表,不带内置排序,如果第一个数字大于第二个数字,则复制并交换它们

Python 从给定的列表中订购一个数字列表,不带内置排序,如果第一个数字大于第二个数字,则复制并交换它们,python,swap,pseudocode,Python,Swap,Pseudocode,我试图以一种方式实现一个函数,即它不使用sorted(lst)或var=lst.copy()而执行与sorted(lst)基本相同的操作,但我就是不知道如何以这种方式工作,并完全按照伪代码中编写的方式进行操作 有人能帮我吗 我的评价是: 下面是排序算法的伪代码: 从列表的开头开始,将每个元素与其下一个相邻元素进行比较 如果该元素大于其下一个相邻元素,请将其更改为其他位置 把清单通读到底 如果在步骤2出现任何混淆,请转至步骤1 我现在的代码: def my_sort(lst): lst_s

我试图以一种方式实现一个函数,即它不使用
sorted(lst)
var=lst.copy()
而执行与
sorted(lst)
基本相同的操作,但我就是不知道如何以这种方式工作,并完全按照伪代码中编写的方式进行操作

有人能帮我吗

我的评价是:

下面是排序算法的伪代码:

  • 从列表的开头开始,将每个元素与其下一个相邻元素进行比较
  • 如果该元素大于其下一个相邻元素,请将其更改为其他位置
  • 把清单通读到底
  • 如果在步骤2出现任何混淆,请转至步骤1
  • 我现在的代码:

    def my_sort(lst):
        lst_sorted = []
        lst2 = lst.copy()
        compare = True
        while compare:
            compare = False
            num = lst2[0]
            if num not in lst_sorted:
                try:
                    for x in lst2:
                        if x < num:
                            x, num = num, x
                            lst_sorted.append(num)
                        elif num < x:
                            compare = True
            else:
                compare = True
        return lst_sorted
    
    直截了当的解决方案 根据您使用标志
    比较
    和准确评估规则的意图,以下是一个逐步说明:

    def my_sort(lst):
        # We copy the list so that the changes are not made in the original variable.
        # We will modify lst2 from now.
        lst2 = lst.copy()
        compare = True
        while compare is True:
            # compare will remain False as long as there is no swapping
            compare=False
            # We walk the list index by index, excepted the last one
            # so we don't get an index error from the last "index+1"
            for i in range(len(lst2)-1):
                # If the first is greater than the second...
                if lst2[i]>lst2[i+1]:
                    # We swap
                    bump = lst2[i]
                    lst2[i]=lst2[i+1]
                    lst2[i+1]= bump
                    # and set compare to True to ask for another iteration of the while loop
                    compare=True
        return lst2
    
    Python中的另一种交换方式 您可以在一行中交换:

    for i in range(len(lst2)-1):
        if lst2[i]>lst2[i+1]:
           lst2[i], lst2[i+1] = lst2[i+1], lst2[i]
           compare=True
    
    优化气泡排序 此排序算法称为
    气泡排序

    有一个优化是基于这样一个观察,即在一次迭代中,最大值总是被带到端槽。因此,在最坏的情况下,通过在每次迭代中提前停止一个索引,可以避免
    (n-1)**2
    索引

    下面是一个经过调整的实现:

    def optimized_sort(lst):
        lst2 = lst.copy()
        compare = True
        #Creating a variable to store the iteration count
        n = 0
        while compare is True :
            compare=False
            # This time, we walk from index 0 to the last index minus the iteration count
            for i in range(len(lst2) - 1 - n):
                if lst2[i]>lst2[i+1]:
                    lst2[i],lst2[i+1] = lst2[i+1], lst2[i]
                    compare=True
            # We increment the iteration count
            n += 1
        return lst2
    
    正如您所看到的,优化后的版本确实性能更好。


    当然,该算法的性能仍然很差,主要用于教育目的。

    我只是在学习python,但这对我来说很有用:

    def my_sort(lst):
        randHolder = []
        for ele in range(len(lst)):
            mini = min(lst)
            giveIndex = lst.index(mini)
            popped = lst.pop(giveIndex)
            randHolder.append(popped)
        lst = randHolder
        return lst
    

    我猜你想用
    def my_sort(lst)开始你的代码:
    ?哎哟,我忘记复制了,我会编辑那一秒。你能使用内置函数吗?如果你可以使用内置函数,你可以使用
    list(set(f))
    。有没有一种特殊的方法可以用来创建一个新的列表,这样就可以返回它,而不必接触给定的参数?我的教授真的没有给出更多的信息。我尝试了多种方法,但它总是返回
    assert lst_output==sorted(lst_test),\f“Error:my_sort({lst_test})返回{lst_output}而不是{sorted(lst_test)}”
    我想他希望我将代码实现为伪代码。如果数字a大于数字b,则将其交换,直到不再可能使用线性搜索算法为止。出于学习目的,不使用“比较”标志执行此任务会更快吗?@KilimanJaro如果要在任何不必要的其他迭代之前检测到列表已排序,则需要在冒泡排序中使用此标志。如果你忽略早期检测和评估的第四步,你完全可以不使用flag来完成它:不要使用while循环,而是使用n-1次迭代的for循环。这显然意味着它会更慢。我能想到的一个例外是,如果列表最初按相反的顺序排序(从大到小)。flag方法将迭代n次:n-1次进行排序,再进行一次检查。no-flag方法将总共迭代n-1次。在这种情况下,它的好处非常小,但在几乎任何其他情况下,no-flag方法都会比较慢。另外,对于这个非常特殊的情况,在优化版本中,可以通过添加条件语句将while循环限制为n-1次迭代。当我运行代码时,教授的
    test\u my\u sort()
    函数失败。有趣。你知道为什么会这样吗?如果您在我的代码中添加“import random”和“lst_test=random.choices(范围(-99100),k=6)”,您将看到它每次都正确地对列表排序。这是因为您执行了
    lst.pop(giveIndex)
    。这将修改给定的参数。
    def my_sort(lst):
        randHolder = []
        for ele in range(len(lst)):
            mini = min(lst)
            giveIndex = lst.index(mini)
            popped = lst.pop(giveIndex)
            randHolder.append(popped)
        lst = randHolder
        return lst