在简书上学到的本知识点。学习传送门
原理:将目标值插入到前面有序的数之中,从而使有序的数多1。
public class InsertSort {
public static void main(String[] args) {
int[] arr = {23,43,12,56,32,18};
InsertSort(arr);
for(int i=0;i<arr.length;i++) {
System.out.println(arr[i]);
}
}
static void InsertSort(int[] a) {
for(int i=1;i<a.length;i++) {
int temp = a[i];
if(a[i]<a[i-1]) {
for(int j=i;j>=0;j--) {
if(j>0&&temp<a[j-1]) {//要插入的数与前面有序的数比较
a[j]=a[j-1];//将比目标值大的值移到后面
}else {
a[j]=temp;//最后将目标值插入
break;//目标值插入后此时已完成当前循环
}
}
}
}
}
}