- 代码实现:
public class 插入排序 {
public static void main(String[] args) {
int[] array={3,44,38,44,72,54,32,43,242,46,47,56};
//定义一个变量去接收无序的起始索引
int startIndex=-1;
//找到无序的那一组数组是从哪个开始
for (int i = 0; i <array.length ; i++) {
if (array[i]>array[i+1]){
startIndex=i+1;
break;
}
}
//遍历无序数组
for (int i = startIndex; i < array.length; i++) {
//记录当前要插入数据的索引
int j=i;
while (j>0&&array[j]<array[j-1]){
int temp=array[j];
array[j]=array[j-1];
array[j-1]=temp;
j--;
}
}
prinyarr(array);
}
private static void prinyarr(int[] array){
for (int i = 0; i <array.length ; i++) {
System.out.println(array[i]);
}
System.out.println();
}
}