Java算法—插入排序(Insertion Sort)

插入排序(Insertion Sort)

插入排序 Insertion Sort

核心思路

基本思想:每一步将一个待排序的数据插入到前面已经排好序的有序序列中,直到插完所有元素为止。

将0索引的元素到N索引的元素看做是有序的,把N+1索引的元素到最后一个当成是无序的。

遍历无序的数据,将遍历到的元素插入有序序列中适当的位置,保持升序排列,如遇到相同数据,插在后面。

插入排序在插入的时候,有优化算法,在遍历有序序列找正确位置时,可以采取二分查找

排序结束后,默认是升序结果。

N的范围:0~最大索引

代码实现

java 复制代码
public class InsetSort {
    public static void main(String[] args) {
        int[] arr = {3,66,55,22,88,11};
        // 1.找打无序的那一组数组是从哪个索引开始的
        int startIndex =-1;
        for (int i = 0; i < arr.length; i++) {
            if (arr[i]>arr[i+1]){
                //无序数组从startIndex索引开始
                startIndex= i+1;
                break;
            }
        }
        // 遍历无序那组数据
        for (int i = startIndex; i < arr.length; i++) {
            // 记录当前无序数组中要插入数据的索引
            int j =i;
            while (j>0 && arr[j]<arr[j-1]){
                // 交换位置
                int temp = arr[j];
                arr[j] = arr[j-1];
                arr[j-1] = temp;
                j--;
            }
        }
        // 遍历输出
        for (int i : arr) {
            System.out.print(i+" ");
        }
    }
}

System.out.print(i+" ");

}

}

}

复制代码
相关推荐
小马爱打代码2 小时前
Spring Boot:模块化实战 - 保持清晰架构
java·spring boot·架构
Zsy_0510032 小时前
【数据结构】二叉树OJ
数据结构
岁忧2 小时前
GoLang五种字符串拼接方式详解
开发语言·爬虫·golang
tyatyatya2 小时前
MATLAB基础数据类型教程:数值型/字符型/逻辑型/结构体/元胞数组全解析
开发语言·matlab
小坏讲微服务2 小时前
SpringBoot4.0整合knife4j 在线文档完整使用
java·spring cloud·在线文档·knife4j·文档·接口文档·swagger-ui
8***Z892 小时前
springboot 异步操作
java·spring boot·mybatis
i***13243 小时前
Spring BOOT 启动参数
java·spring boot·后端
坚持不懈的大白3 小时前
后端:SpringMVC
java
IT_Octopus3 小时前
(旧)Spring Securit 实现JWT token认证(多平台登录&部分鉴权)
java·后端·spring
kk哥88993 小时前
Spring详解
java·后端·spring