package Sort;
public class Insert {
public static void main(String[] args) {
int[] a = {38,5,47,15,36,26,27,2,46,4,19,50,48};
int i,j,temp;
for(i = 1;i < a.length;i++){
temp = a[i];
// for(j = i-1;j >= 0;j--){ //错误的!!!!
// if(temp > a[j]){
// a[j+1] = temp;
// break;
// }
// else
// a[j+1] = a[j];
// }
// for(j = i-1;j >= 0 && temp < a[j];j--){ //for循环正确
// a[j+1] = a[j];
// }
// a[j+1] = temp;
j = i-1; //while循环正确!
while(j >= 0 && temp < a[j] ){ //条件的顺序很重要!!
a[j+1] = a[j];
j--;
}
a[j+1] = temp;
}
for(i = 0;i < a.length;i++)
System.out.print(a[i]+" ");
}
}
插入排序
最新推荐文章于 2023-09-23 17:47:53 发布