Simple analysis and sample code using the insert sorting algorithm in Python

Source: Internet
Author: User
This article mainly introduces the simple analysis and code example of using the Insertion sorting algorithm in Python. The average time complexity of the insertion algorithm is O (n ^ 2). For more information, see Problem Description

Sorts random numbers in ascending order.

Insert algorithm

Take a number from the array each time, compare it with the existing number, and insert the appropriate position.

In this case, the existing numbers can be sorted in order each time until the numbers are obtained, that is, they are sorted successfully.

This is very similar to card capturing during cards,

First condition: the order of cards on hand is correct.
The second condition: each time a new card is caught, it is inserted in the middle of the card in order.
To ensure that the two cards remain unchanged, no matter how many cards are captured, the cards at the end are arranged in order.

Python implementation:

Def insertion_sort (n): if len (n) = 1: return n B = insertion_sort (n [1:]) m = len (B) for I in range (m): if n [0] <= B [I]: return B [: I] + [n [0] + B [I:] return B + [n [0]


Another version:

Def insertion_sort (lst): if len (lst) = 1: return lst for I in xrange (1, len (lst )): temp = lst [I] j = I-1 while j> = 0 and temp <lst [j]: lst [j + 1] = lst [j] j-= 1 lst [j + 1] = temp return lst


For more details about the simple analysis and sample code of the inserted sorting algorithm in Python, please follow the PHP Chinese network!

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.