A simple analysis and code example using the Insert sort algorithm in Python

Source: Internet
Author: User
Problem description

A set of randomly arranged numbers is re-arranged in small to large order.

Insert algorithm

Each time a number is taken from the array, compared to the existing number and inserted in the appropriate position.

So repeat, each time you can keep the existing numbers in order, until the numbers are finished, the sorting is successful.

It's a lot like a poker-card situation,

First condition: Keep the hands on the cards in the correct order
The second condition: each time the new cards are caught in order to insert the hand in the middle of the card.
Ensure that these two are not changed, then no matter how many cards are caught, the cards in the final hand are arranged in order.

Python implementations:

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] &l t;= 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


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.