/**
* 插入排序的思想好比对手中的扑克牌排序;
* 好比左手为空,桌面牌面朝下,我们每次拿
* 起一张桌面的牌,将其插入左手正确的位置,
* 在插入过程中,将被插入的牌按某一顺序逐个
* 和左手的牌比较,找到正确的位置就停止
* **/
//<strong><span style="font-size:18px;">伪代码如下:</span></strong>
/**
* insertion_sort()
* for j=2 to a.length
* key=A[j]
* //insert A[j] into the sorted sequence A[1,2...,j-1]
* i=j-1
* while i>0 and A[i]>key
* A[i+1]=A[i]
* i=i-1
* A[i+1]=key
* **/
</pre><pre name="code" class="java">//Java实现如下:
public class Insertion_sort{
public static void sort(Comparable[] a)
{
//将a[]按升序排列
int N=a.length;
for(int i=2;i<N;i++)
{
for(int j=i;j>0&&(a[j].compareTo(a[j-1])<0);j--)
{Comparable t=a[j];
a[j]=a[j-1];
a[j-1]=t;
}
}
}
}
算法性能:
对于随机排列的长度为N且主键不重复的的数组,平均情况下插入排序需要(N^2)/4次比较和(N^2)/4次交换。最好情况
只需要N-1次比较,0次交换