直接插入算法的描述:将第i个元素插入到前i个元素构成的序列前,然后通过比较大小移动i得到适当位置。
本人的模拟代码如下:
public class InsertSort {
public static int[] random(int n){
if(n>0){
int table[] =new int[n];
for(int i=0;i<n;i++){
table[i]=(int) (Math.random()*100);
}
return table;
}
return null;
}
public static void print(int[] table){
String result="";
for(int i=0;i<table.length;i++){
result+=table[i]+" ";
}
System.out.println(result);
}
public static void insertSort(int[] table){
for(int i=1;i<table.length;i++){
int temp=table[i],j;
for(j=i-1;j>-1&&temp<table[j];j--)
table[j+1]=table[j];
table[j+1]=temp;
System.out.print("第"+i+"趟: ");
print(table);
}
}
public static void main(String[] args){
int[] table=InsertSort.random(8);
System.out.print("关键字序列:");
InsertSort.print(table);
InsertSort.insertSort(table);
}
}
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
结果:
关键字序列:83 52 20 46 41 42 24 22
第1趟: 52 83 20 46 41 42 24 22
第2趟: 20 52 83 46 41 42 24 22
第3趟: 20 46 52 83 41 42 24 22
第4趟: 20 41 46 52 83 42 24 22
第5趟: 20 41 42 46 52 83 24 22
第6趟: 20 24 41 42 46 52 83 22
分析:
最好的情况:
数据序列已排序,每一趟比较,移动2次。总比较次数为n-1,总移动次数:2(n-1),因此时间复杂度为O(n)。
最坏的情况:
数据序列反序排列,第i趟插入元素比较次数为i,移动次数为i+2。总比较次数为n^2/2,总移动次数n^2/2。时间复杂度为O(n)。
数据序列随机排列:
查找一个元素平均比较的次数是(i+1)/2,插入一个元素平均移动的次数i/2。总的比较次数n^2/4,移动次数n^2/4,复杂度为O(n).