直接插入排序

来源:互联网 发布:网站流量数据分析 编辑:程序博客网 时间:2024/05/18 17:59
直接插入排序就是 每插入一个新数的时候重新排一次序.

假如有5个数 5 3 4 1 2,要求按照从小到大排序,那么直接插入的思想是这样的,
我们先假设起始状态下我们只有5这一个数的数组,
然后有个数3要插入这个数组,这时我们已经默认数组有俩个数了,
就是{5 ,_},然后比较,5>3,那么将5赋值给3这个位置,变成{5,5},再将拿出去的3放回5原来的位置去,
变成{3,5}.
......
我们假如已经排到这样 3,4,5,1,2,那么数1拿出来,{3,4,5,_,2},其实我们根本不需要看1后面的数,我们重点关注前面的这些数也就是{3,4,5_}和要插入的1,这样5>1则5向前进一位,变成{3,4,5,5}(这里把1放不放到5原来的位置都不影响结果,因为我们关心的是已经进位的数),然后4>1则4向前进一位,变成{3,4,4,5},同理3进一位变成{3,3,4,5},最后比较最终停在了3原来的位置上,把1放到3原来的位置上变成{1,3,4,5},所以原有的数组变成{1,3,4,5,2}

public static void main(String args[]) throws Exception {
int a[] = { 1, 19, 3, 16, 16, 5, 1, 15, 18, 7, 2, 2, 6, 13, 17, 6, 18, 4, 3, 10 };
// for (int i = 0; i < 20; i++) {//生成随机数
// System.out.print(Random.class.newInstance().nextInt(20) + ",");
// }
straightSort(a);
for (int i : a) {
System.out.print(i + ",");
}
}

几种形式:
第一种:
public static void straightSort1(int a[]) {
int temp;
int j;
for (int i = 1; i < a.length; i++) {
temp = a[i];
for (j = i - 1; j >= 0 && a[j] > temp; j--) {
a[j + 1] = a[j];
}
a[j + 1] = temp;
}
}
第二种:
这一种就是把上面for里面的条件拆开写了而已
public static void straightSort2(int a[]) {
int temp = 0;
int j;
for (int i = 1; i < a.length; i++) {
temp = a[i];
for (j = i - 1; j >= 0; j--) {
if (a[j] > temp) {
a[j + 1] = a[j];
} else
break;
}
a[j + 1] = temp;
}
}
第三种:
这一种就是上面括号里面说的((这里把1放不放到5原来的位置都不影响结果,因为我们关心的是已经进位的数))
public static void straightSort3(int a[]) {
int temp = 0;
int j;
for (int i = 1; i < a.length; i++) {
temp = a[i];
for (j = i - 1; j >= 0; j--) {
if (a[j] > temp) {
a[j + 1] = a[j];
a[j] = temp;//这里放回去了,所以最后不用放了,缺点就是每次都要放回去
}
else break;
}
}
}
三种其实都有break的思想,那是因为我们不管插入哪个数,那么之前已经插入数后的数组其实已经是排序好的数组了,再插入的时候,只要遇到一个比他小的数x,那么x之前的数只能更小,无需比较了(当然比较也不会错).
0 0
原创粉丝点击