代码
总体思想:
由少入多的来说
int[] a = {5, 3};
已插入排序的思想来说,角标为0,即5自然没什么好的,当到3的时候,把3记录下来,temp = 3,将数组中的3换成5,a[1] = 5,你可以把它理解成将前面的数据往后挪了一位,最后将数组中5的位置换成3
int[] a = {5, 3, 4};
这里,我们跨过上面的步骤,把它看成 int[] a = {3, 5, 4}, 同样的记录住4,temp =4,在往后依次复制的过程中,发现3<4,那么直接就跳过去,最后是 {3, 4, 5};
int[] a = {5, 3, 2};
int[] a = {3, 5, 2},记录2 temp = 2,5>2所以a[2] = a[1],3>2所以a[1] = a[0]
写一段伪代码:
int temp = 0;
for (int i = 0; i < a.length; i++) {
temp = a[i];//记录当前位置的值
int j = i-1;
/**
* 往后复制值的代码
*/
for (; j >= 0 && temp < a[j]; j--) {
a[j+1] = a[j];//第一个循环,就是将 i 的值覆盖掉
}
//复制完毕,将temp值赋值给最小角标处
a[j+1] = temp;
}
example:
private void sort() {
int[] a ={12, 5, 18, 24, 19, 7, 4};
int temp = 0;
for (int i = 0; i < a.length; i++) {
temp = a[i];
int j = i-1;
for (; j >= 0 && temp < a[j]; j--) {
a[j+1] = a[j];
}
a[j+1] = temp;
}
for (int i : a) {
System.out.println(i+"--");
}
}