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