package insert;
import util.ArrayUtil;
public class InsertSort {
public static void main(String[] args) {
/**
* 判断索引为j和索引为j-k的值,如果索引为j的值大于索引为j-k的值,就不用换为位置,直接退出内循环,否则就交换位置, 直到j-k为0。
*
*/
int[] intArrayForSort = ArrayUtil.getRandomArray();
int i = 1, k, j = 1;
long t = System.currentTimeMillis();
for (i = 1; i < intArrayForSort.length; i++) {
int minValue = intArrayForSort[j];// 假设索引为j的数字是最小的。
k = 1;
do {
if (minValue < intArrayForSort[j - k]) {// intArrayForSort[j -
// k]大于【临时最小值】,
// 但【临时最小值】要插入的位置并不一定就在这个位置,所以要互换他们的位置。
// **********begin*************
int temp = intArrayForSort[j - k + 1];// j - k + 1最不好理解的地方
intArrayForSort[j - k + 1] = intArrayForSort[j - k];
intArrayForSort[j - k] = temp;
// ***********end**************
// begin和end的代码块目的是将2个数字的位置互换。
} else {// 临时最小值比已经排序好的数组中的最大值还大或者相同,直接退出内循环。
break;
}
k++;
} while ((j - k) >= 0);
// 内循环的作用是:判断索引为j-k的值是否比 【临时的最小值 】大。
j++;
}
System.out.println("\r<br>执行耗时 : " + (System.currentTimeMillis() - t)
/ 1000f + " 秒 ");
for (int printI = 0; printI < intArrayForSort.length; printI++) {
// System.out.println(intArrayForSort[printI]);
}
InsertSort1(null);
}
/*
* 百度百科的参考例子。例子是找到需要的插入的位置的索引,然后将保存起来的值插进去。 而我的这个是每次都对比最小值,然后将2个值互换。 *
*/
public static void InsertSort1(int[] a) {
a = ArrayUtil.getRandomArray();
if (a != null) {
long t = System.currentTimeMillis();
for (int i = 1; i < a.length; i++) {
int temp = a[i], j = i;// 将需要插入的数值保存起来
if (a[j - 1] > temp) {
// 将符合条件的数往后挪。符合的条件包括:1、需要插入的数值要比需要挪的最后一个数字小
// 2、往后挪的最后一个数字的索引必须大于0
while (j >= 1 && a[j - 1] > temp) {
a[j] = a[j - 1];// 数值往后挪
j--;
}
a[j] = temp;
}
}
System.out.println("\r<br>执行耗时 : "
+ (System.currentTimeMillis() - t) / 1000f + " 秒 ");
} else {
System.out.print("array hasn't bean inited!");
}
}
}
效率比百度百科的差了N百倍!!!!百度百科的只需要查找合适的一个索引即可,而我的需要将子数组往后挪动。