Python sorting algorithm - insertion sort


principle

The working principle of insertion sorting is to construct an ordered sequence. For unsorted data, scan from the back to the front in the sorted sequence, find the corresponding position and insert it. In the implementation of insertion sorting, in-place sorting is usually used, so in the process of scanning from back to front, it is necessary to repeatedly shift the sorted elements backwards gradually to provide insertion space for the latest elements.


Animation presentation

insert image description here

Two, the code

1. Insertion sort

The code is as follows (example):

def insertion_sort(nums):
    """
    :param nums: 无序数组
    :return:
    """
    for i in range(1, len(nums)):
        for j in range(i, 0, -1):
            print(j, nums[j], nums[j - 1])
            if nums[j] < nums[j - 1]:
                nums[j], nums[j - 1] = nums[j - 1], nums[j]
            else:
                break
            print(nums)
    return nums


if __name__ == '__main__':
    arr = [12, 11, 13, 5, 6]
    insertion_sort(arr)
    print("排序后的数组:", arr)

Time complexity:
O(n2).


Summarize

Work essay, I hope it can help everyone!
If there are deficiencies, please advise!

Guess you like

Origin blog.csdn.net/black_lightning/article/details/115789618