上篇我们简单的解说了插入算法,还不清楚的小伙伴可以留言沟通
今天我们来用java实现这个算法,直接上代码
package ttt;
public class test {
public static void getInsertSort(int[] a) {
if(a == null || a.length == 0) {//判断是否是个有值数组
System.out.println("该数组不存在或者没有值!");
return;
}
int n = a.length;//将数组的长度赋给n是为了防止每次for循环中判断时都调用length方法影响性能
int tmp;//用于中转数据
int j;
for(int i = 1; i < n;i++){//排序的次数
tmp = a[i];
for(j = i-1; j>=0 && a[j]>tmp; j--) {//取i前面的所有跟i位置元素进行比较,先比较i-1和i,如果i-1大于i,则互换位置,i-1和i-2比较,以此类推
a[j+1] = a[j];
}
a[j+1]= tmp;
System.out.println("============="+tmp);
for(int m = 0; m < a.length; m++) {
System.out.print(a[m] + " ");
}
System.out.println("\n");
}
}
public static void main(String[] args) {
int[] a = {10,9,7,5,6,3};
System.out.print("之前的排序:");
for(int i = 0; i < a.length; i++) {
System.out.print(a[i] + " ");
}
getInsertSort(a);
System.out.print("直接插入排序:");
for(int i = 0; i < a.length; i++) {
System.out.print(a[i] + " ");
}
}
}
运行结果如下
之前的排序:10 9 7 5 6 3 =============9
9 10 7 5 6 3
=============7
7 9 10 5 6 3
=============5
5 7 9 10 6 3
=============6
5 6 7 9 10 3
=============3
3 5 6 7 9 10
直接插入排序:3 5 6 7 9 10
实现了我们想要的效果