原理:假定从小到大排序,从第二个数开始,把当前的数用一个变量temp保存起来,然后倒序依次跟前面的数比较,较大的数依次往后移,找到自己要插入的地方将数插入。如此往返循环将所有的树插入进去。 时间复杂度 O(n^2)
public class InsertionSort{
public static void main(String[] args) {
int[] a = new int[20];
Random r = new Random();
for(int i =0 ;i<a.length;i++){
a[i] = r.nextInt(100);
System.out.print(a[i]+" ");
}
System.out.println();
insertSort(a);
for(int num : a){
System.out.print(num + " ");
}
}
public static void insertSort(int[] a){
for(int i=1;i<a.length;i++){
int temp = a[i];
int j=i-1;
while(j>=0 && a[j]>temp){
a[j+1]=a[j];
j--;
}
a[++j]=temp;
}
}
}