1.原理:从原数组中依次取出数据,按照大小找到新数组的位置,然后插入进去
2.代码实现
/**
* 插入排序
*/
public class InsertSort {
public static void main(String[] args) {
int[] array = new int[]{6546,54654,4654654,4544,2132,224,2432,44,4525,465465,46,6446,44646};
int[] temp = insertSort(array);
for(int a : temp){
System.out.println(a);
}
}
private static int[] insertSort(int[] arr){
int[] temp = null;
for(int a : arr){
//当temp为空时,初始化temp
if(temp == null){
temp = new int[]{a};
continue;
}
//如果a大于temp的最大值,直接扩容temp,然后将a放在temp最后的位置,继续循环
if(a >= temp[temp.length-1]){
temp = Arrays.copyOf(temp, temp.length+1);
System.arraycopy(temp,0,temp,0,temp.length);
temp[temp.length-1] = a;
continue;
}
//如果a小于temp最小值,直接扩容temp,将temp数据全部后移一位,然后把a放在第一位,继续循环
if(a < temp[0]){
temp = Arrays.copyOf(temp, temp.length+1);
System.arraycopy(temp,0,temp,1,temp.length-1);
temp[0] = a;
continue;
}
for(int i = 0; i< temp.length-1; i++){
//扩容,然后将i之后的数据全部后移一位,将a放入i+1的位置
if (a >= temp[i] && a < temp[i+1]) {
temp = Arrays.copyOf(temp, temp.length+1);
System.arraycopy(temp,i+1,temp,i+2,temp.length-i-2);
temp[i+1] = a;
break;
}
}
}
return temp;
}
}