Python algorithm-Insert sort

Source: Internet
Author: User

Insert Sort

The core idea: in an ordered array, the position of the new number is found by comparing one to the previous number.

Example: An array has a number 21

Insert a 3,3<21, so the result is 3,21

then insert a 34,34>21, So the result is 3,21,34

then insert a 6,34>6, move forward,21>6, move forward,3<6, So the result is 3,6,21,34

question 1: How many times do you need to insert an array with n numbers to complete the insertion sort?

N-1 Times

Second, the core code:

def insert_sort (lista):

For I in Xrange (1,len (Lista)): # use i to control the subscript from the second number to the last number

j = i-1 # with J to control I front one number and i do compare

While J >= 0: #j <0 is a decision condition for exit loops

If LISTA[J] > lista[j+1]: # If the first number is greater than the last number, swap position

LISTA[J],LISTA[J+1] = Lista[j+1],lista[j]

J-= 1 #j minus one to compare to the previous value

Else

Break # As soon as there is a j>j+1, swap out this cycle can be

return lista

if __name__ = = ' __main__ ':

Print Insert_sort ([2,15,6,29,0])

Three, time complexity:

worst case comparison 1+2+ ... +n-2 + n-1 = N (n-1)/2 N^2/2

the best comparison situation is n-1 ..... exactly in the corresponding position

The average situation is [N (n-1)/2 + (n-1)]/2 = N^2/4

The final result is O (n^2)

Python algorithm-Insert sort

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.