简体   繁体   English

python中插入排序算法的实现

[英]Implementation of Insertion Sort Algorithm in python

I was trying to implement the insertion sort algorithm in python and was able to code it as below, I am not getting the whole array sorted and was wondering if this implementation has the proper thought process behind it, if not I would greatly appreciate if someone can help me in understanding it as the function is considering the sorted part of the array when inserting an element from the unsorted part.我试图在 python 中实现插入排序算法并能够将其编码如下可以帮助我理解它,因为该函数在从未排序部分插入元素时正在考虑数组的排序部分。 Also, in your review kindly consider if the implementation is correct and if so what can make my solution output correct.此外,在您的评论中,请考虑实施是否正确,如果正确,什么可以使我的解决方案输出正确。

def insertion_sort(array):
    for i in range(1, len(array)):
        for j in reversed(range(1, i)):
            if array[j-1] > array[j]:
                temp = array[j-1]
                array[j-1] = array[j]
                array[j] = temp
    return array

to_sort = [4, 3, 1, 5, 6, 2]
print(insertion_sort(to_sort))

This is the output I got: [1, 3, 4, 5, 6, 2]这是我得到的输出: [1, 3, 4, 5, 6, 2]

tl;dr: Insertion Sort algorithm not giving perfect output. tl; dr:插入排序算法没有给出完美的输出。 Is implementation correct and what can be done to fix the output.实施是否正确以及可以做些什么来修复输出。

You are never touching the last element of the array, I suggest changing len(array) with len(array)+1 , ie,您永远不会触及数组的最后一个元素,我建议将len(array)更改为len(array)+1 ,即

def insertion_sort(array):
    for i in range(1, len(array)+1):
        for j in reversed(range(1, i)):
            if array[j-1] > array[j]:
                temp = array[j-1]
                array[j-1] = array[j]
                array[j] = temp
    return array

This is because i has maximum value len(array)-1 and j has as maximum value i-1 , which is len(array)-2 .这是因为i具有最大值len(array)-1并且j具有最大值i-1 ,即len(array)-2 However, the last element in the array has index len(array)-1 .但是,数组中的最后一个元素具有索引len(array)-1

The goal of your function would be to shift array[i] into the sorted partition, but it actually does that for array[i-1] , because the inner loop starts with j equal to i-1 .您的函数的目标是将array[i]转移到已排序的分区中,但它实际上对array[i-1]执行此操作,因为内部循环以j等于i-1开始。

So the easy fix is to change:因此,简单的解决方法是更改​​:

    for j in reversed(range(1, i)):

to:至:

    for j in reversed(range(1, i + 1)):

Improvements改进

More Pythonic would be to use the capability of range to produce a descending range:更多的 Pythonic 将是使用range的能力来产生一个递减的范围:

    for j in range(i, 0, -1):

When the if condition is not true, it is useless to continue the inner loop, as then it is guaranteed that the if condition will never be true in the rest of the inner loop's iterations.if条件不成立时,继续内循环是没有用的,因为这样可以保证if条件在其余的内循环迭代中永远不会为真。 So add a break:所以添加一个休息:

        if array[j-1] <= array[j]:
            break
        temp = array[j-1]
        array[j-1] = array[j]
        array[j] = temp

As these swaps will always move the same value to the left, ie array[j] will always be the value that originally was at array[i] , it is less costly to first find the index where array[i] should be moved to, and then perform a single rotation to get it there.由于这些交换将始终将相同的值向左移动,即array[j]将始终是最初位于array[i]的值,因此首先找到应将array[i]移动到的索引的成本更低,然后执行一次旋转以到达那里。

def insertion_sort(array):
    for i in range(1, len(array)):
        temp = array[i]
        for k in range(i - 1, -1, -1):
            if array[k] <= temp:
                break
        else:
            k = -1
        # rotate
        array[k+2:i+1] = array[k+1:i]
        array[k+1] = temp
    return array

I used k here, so not to confuse it with the meaning of j in the original code: k is j - 1 .我在这里使用了k ,所以不要将它与原始代码中j的含义混淆: kj - 1

This search for k (or j ) can be done with a call to next :可以通过调用next来完成对k (或j )的搜索:

def insertion_sort(array):
    for i in range(1, len(array)):
        temp = array[i]
        j = 1 + next((k for k in range(i - 1, -1, -1) if array[k] <= temp), -1)
        array[j+1:i+1] = array[j:i]
        array[j] = temp
    return array

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

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