排序算法之插入排序

从第二个数开始插入,依次判断相邻两数大小,如果后面的数比前面的数小,进行插入
例:int[] array=new{5,1,3,2,4}
第一次结果:{1,5,3,2,4}
第二次结果:{1,3,5,2,4}
第三次结果:{1,2,3,5,4}
第四次结果:{1,2,3,4,5}

public void insert(int[] array){
for(int i=0;i<array.length-1;i++){//需要插入多少次
//赋值,第一次从第二个数开始往里面插,与第一个数相比较
int insertVal=array[i+1];
int insertIndex=i;
while(insertIndex>=0&&insertVal<array[insertIndex]){
//换位置
array[insertIndex+1]=array[insertIndex];
insertIndex--;
}
array[insertIndex+1]=insertVal;
}
}

全部评论

相关推荐

12-15 14:16
门头沟学院 Java
回家当保安:发offer的时候会背调学信网,最好不要这样。 “27届 ”和“28届以下 ”公司招聘的预期是不一样的。
实习简历求拷打
点赞 评论 收藏
分享
烤点老白薯:他第二句话的潜台词是想让你帮他点个瑞幸或者喜茶啥的
mt对你说过最有启发的一...
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务