插入排序—Java

插入排序

基本思想 :

  • 实现数组从小到大排
  • 从第二个数开始跟前面的数比较 找到合适的位置插入 后面的数往后推移 但推移不会超过原来插入的数的下标

代码实现

java 复制代码
public static void InsertSort(int[] arr) {
		for(int i = 1;i<arr.length;i++) {//从1开始是因为要和前面的数有一个比较的过程
			int InsertIndex=i-1;//要插入的理想目的地
			int Insertvalue= arr[i];
			while (InsertIndex>=0&&Insertvalue<arr[InsertIndex]) {
				//insertindex后移动一位
				arr[InsertIndex+1]=arr[InsertIndex];
				InsertIndex--;
				//一直在减去,所以while结束后代表找到
				//后面要加还给他,代表找到的那个位置
			}
		//
			if(InsertIndex+1!=i) {
				//+1代表找的那个位置
				arr[Insertvalue+1]=Insertvalue;
			}
		}
		for(int i = 0;i<arr.length;i++) {
			System.out.print(arr[i]+"\t");
		}
		
		
	}
相关推荐
zjttsh13 分钟前
Linux下安装Redis
java
回敲代码的猴子24 分钟前
2月14日打卡
算法
TimberWill37 分钟前
SpringBoot整合Srping Security实现权限控制
java·spring boot·后端
blackicexs1 小时前
第四周第七天
算法
期末考复习中,蓝桥杯都没时间学了1 小时前
力扣刷题19
算法·leetcode·职场和发展
Renhao-Wan2 小时前
Java 算法实践(四):链表核心题型
java·数据结构·算法·链表
zmzb01033 小时前
C++课后习题训练记录Day105
开发语言·c++·算法
_codemonster3 小时前
JavaWeb开发系列(六)JSP基础
java·开发语言
万邦科技Lafite3 小时前
淘宝店铺所有商品API接口实战指南
java·数据库·mysql
好学且牛逼的马3 小时前
【Hot100|25-LeetCode 142. 环形链表 II - 完整解法详解】
算法·leetcode·链表