Home  >  Article  >  Backend Development  >  [Insertion sort implementation] python

[Insertion sort implementation] python

不言
不言Original
2018-05-05 14:53:401522browse

This article shares with you the code for insertion sort implementation in Python. Friends who are interested can take a look at

Thoughts:

It is similar to sorting out cards: take out one card, insert it into the correct position in the hand (compare it with each card in the hand from right to left)

Insertion sorting pseudo code:

INSERTION-SORT(A)
for j <-- 2 to length[A]
    do key <-- A[j]
    i <-- j-1
    while i>0 and A[i]>key
        do A[i+1] <-- A[i]
            i <-- i-1
    A[i+1] <--  key
python实现:
def insertion_sort(A)
    for j in range(1 , len(A));
    key = A[j]
    i = j - 1
    while i>=0 and A[i]>key;
        A[i+1] = A [i]
        i = i - 1
    A[i+1] = key
A = [5,2,4,6,1,3]
insertion_sort(A)
print(A)


The above is the detailed content of [Insertion sort implementation] python. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn