插入排序 insertion sort

INSERTION-SORT( A)
1   for  j ← 2  to length[A]
2        do key  ← A[j]
3               //Insert  A[j] into the sorted sequence A[1   j - 1].
4               i ← j - 1
5               while  i > 0 and A[i] > key 
6                     do A[i + 1] ← A[i]
7                            i ← i - 1
8               A[i + 1] ← key  
 分析
  1、数组A分三部分: A[i .. j-1]已排好序,A[j]待插入,A[j+1 .. n]未排序
  2、插入排序是一个数组内的排序,排序过程中有O(1)个元素在数组外。

示例:

数组:A = [5, 2, 4, 6, 1, 3]

时间分析
最好的情况
     数组已经排好序了,运行时间可以表示为 an+b,它是n的线性函数
最坏的情况
     数组时倒叙的,运行时间可以表示为an2+bn+c,它是关于n的二次函数。
 
插入排序的最坏情况时间代价为 O(n2)
原文地址:https://www.cnblogs.com/windlaughing/p/3092689.html