简体   繁体   English

使用 for 循环在 Python 中插入排序

[英]Insertion Sort in Python with for loops

I'm learning Python from a web source which implemented the Insertion Sort algorithm using a combination of for loop and while loop.我正在从 web 源学习 Python,它使用 for 循环和 while 循环的组合实现了插入排序算法。 I thought of practicing the code by myself and I coded an algorithm using only for loops.我想自己练习代码,我只使用 for 循环编写了一个算法。 I need some feedback on whether my code is correct, and whether its valid.我需要一些关于我的代码是否正确以及是否有效的反馈。

def insertionSort(lst):
    for i in range(1,len(lst)):
        temp = lst[i]

        for j in range(0,i):
            if lst[j] > temp:

                lst[i], lst[j] = lst[j], lst[i]
        
    return lst

lst = [8, 6, 4, 20, 24, 2, 10, 12]
print(insertionSort(lst))

The output is: [2, 4, 6, 8, 10, 12, 20, 24] output 是:[2, 4, 6, 8, 10, 12, 20, 24]

Your algorithm could be called insertion sort in a broad sense, but it is different from what is commonly understood by insertion sort, as it compares the temp value with all previous values, while standard insertion sort only compares temp with the greater values among the previous values, and with one additional value that will become temp 's predecessor (if there is one).您的算法广义上可以称为插入排序,但它与通常理解的插入排序不同,因为它会将temp值与之前的所有值进行比较,而标准插入排序只会将temp与之前的较大值进行比较值,以及一个附加值,它将成为temp的前身(如果有的话)。

This means your implementation will have a best case time complexity that is O(²), while the best case time complexity of the standard algorithm is O().这意味着您的实现的最佳情况时间复杂度为 O(²),而标准算法的最佳情况时间复杂度为 O()。 That best case occurs when the input is already sorted.最好的情况发生在输入已经排序的时候。

The typical insertion sort algorithm will have the inner loop going backwards, visiting values in descending order, and stopping when it finds a value that is less than (or equal to) the value to move ( temp ).典型的插入排序算法将使内部循环向后进行,按降序访问值,并在找到小于(或等于)要移动的值 ( temp ) 的值时停止 During this loop the swaps are done with 2 consecutive values, and this can be improved by delaying the insertion of temp so that values only have to be copied one place to the right until the insertion point is found.在这个循环中,交换是用 2个连续的值完成的,这可以通过延迟插入temp来改进,这样值只需要向右复制一个位置,直到找到插入点。

An implementation of that in Python could look like this: Python 中的实现可能如下所示:

def insertionSort(lst):
    for i, temp in enumerate(lst):
        for j in range(i - 1, -1, -1):
            if lst[j] <= temp: # Found insertion point?
                lst[j + 1] = temp
                break
            lst[j + 1] = lst[j] # Make room for temp
        else: # temp is the least value so far: insert at the start
            lst[0] = temp
        
    return lst

Correctness testing正确性测试

To test yourself whether your implementation correctly sorts a list, you can bombard your function with random input.要测试您的实现是否正确地对列表进行排序,您可以用随机输入轰炸您的 function。 For instance like this:例如像这样:

import random

for size in range(100):
    lst = list(range(size))
    random.shuffle(lst)
    finallist = lst[:]
    insertionSort(finallist)
    if finallist != sorted(finallist):
        print("Not sorted correctly:", lst, "to", finallist)
        break
else:
    print("All tests passed successfully")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM