设 待排序数组长度为10
a[0] | a[1] | a[2] | a[3] | a[4] | a[5] | a[6] | a[7] | a[8] | a[9] |
将数组从小到大排序。
像打扑克时,对扑克牌排序一样,
手里已有的牌已完成从小到大排序(手里只有一张牌,也为有序)
对于新取到的牌,与已有的牌从右至左依次对比并根据大小交换,无需交换时,取下一张牌。
public static void InsertSort(int [] data){
for (int i=1;i<data.length;i++){ // 从第data[1]开始取牌,取到data[9]。
//将取到的牌依次与已有的牌从右向左对比,比取到的牌大,就交换位置;比取到的牌小停止。
for (int j=i;j>0 && data[j-1]>data[j];j--){
int temp;
temp = data[j];
data[j]=data[j-1];
data[j-1]=temp;
}
}
}
/
//上面的程序插入时(第二个for循环),总是在执行对比后插入,对比后插入,比较费时
//下面的程序把手里已有的牌与取到的牌对比,最后再插入取到的牌
public static void InsertSort(int [] data){
for (int i=1;i<data.length;i++){ // 从第data[1]开始取牌,取到data[9]。
//先设置一个临时变量保存要插入的扑克牌
int temp = data[i];
//从取到的data[i]位置开始
int j=i;
//将取到的牌依次与已有的牌从右向左对比,比取到的牌temp=data[i]大,就将已有的牌往右移;比取到的牌小时停止。
for (;j>0 && data[j-1]>temp;j--){
data[j]= data[j-1];
}
//把取到的牌temp插入
data[j]=temp;
}
}
3 | 0 | 1 | 8 | 7 | 2 | 5 | 4 | 9 | 6 |
手里只有一张【3】时,也为有序的扑克牌
3 | 0 | 1 | 8 | 7 | 2 | 5 | 4 | 9 | 6 |
【0】----->【3】
0 | 3 | 1 | 8 | 7 | 2 | 5 | 4 | 9 | 6 |
【1】----->【3】----->【1】
0 | 1 | 3 | 8 | 7 | 2 | 5 | 4 | 9 | 6 |
【8】----->【3】
0 | 1 | 3 | 8 | 7 | 2 | 5 | 4 | 9 | 6 |
【7】----->【8】----->【3】
0 | 1 | 3 | 7 | 8 | 2 | 5 | 4 | 9 | 6 |
【2】----->【8】----->【7】----->【3】----->【1】
0 | 1 | 2 | 3 | 7 | 8 | 5 | 4 | 9 | 6 |
【5】----->【8】----->【7】----->【3】
0 | 1 | 2 | 3 | 5 | 7 | 8 | 4 | 9 | 6 |
【4】----->【8】----->【7】----->【4】----->【3】
0 | 1 | 2 | 3 | 4 | 5 | 7 | 8 | 9 | 6 |
【9】----->【8】
0 | 1 | 2 | 3 | 4 | 5 | 7 | 8 | 9 | 6 |
【6】----->【9】----->【8】----->【7】----->【5】
0 |
下面为插入排序算法舞蹈
https://v.youku.com/v_show/id_XMTY0NjQ2ODY5Ng==.html?spm=a2h0j.11185381.listitem_page1.5!25~A