java实现插入排序

图解

以下是Java实现插入排序的代码:

java 复制代码
public class InsertionSort {
    public static void main(String[] args) {
        int[] arr = {5, 2, 4, 6, 1, 3};
        insertionSort(arr);
        System.out.println(Arrays.toString(arr)); // output: [1, 2, 3, 4, 5, 6]
    }

    public static void insertionSort(int[] arr) {
        int n = arr.length;
        for (int i = 1; i < n; i++) {
            int key = arr[i];
            int j = i - 1;
            while (j >= 0 && arr[j] > key) {
                arr[j + 1] = arr[j];
                j--;
            }
            arr[j + 1] = key;
        }
    }
}

在插入排序中,我们从第二个元素开始,将其与已排序好的子数组中的元素进行比较,并将其插入到合适的位置中。在这个过程中,我们需要不断地向前移动已排序好的子数组中的元素,以为这个新的元素腾出位置。

相关推荐
计算机学姐1 分钟前
基于SpringBoot的房屋交易系统
java·vue.js·spring boot·后端·spring·intellij-idea·mybatis
CQU_JIAKE11 分钟前
4.12[A]
java
小二李12 分钟前
什么是依赖注入(DI)&控制反转IoC
java·开发语言
今夕资源网16 分钟前
indextts API 阅读 API 重磅升级!低延迟 + 音色管理 + 缓存全拉满 支持开源阅读小说软件,其他软件应该也通用
java·后端·spring
智者知已应修善业17 分钟前
【51单片机非精准计时2个外部中断启停】2023-5-29
c++·经验分享·笔记·算法·51单片机
是宇写的啊21 分钟前
SpringIoc和Di
java·开发语言
QQ6765800825 分钟前
基于YOLO26算法的智慧农业橙子图像识别 橙子采摘识别 水果采摘识别 高清采摘过程图像识别 YOLO+voc个数据集第10410期
算法·yolo·橙子采摘·水果采摘识别·高清采摘过程图像识别
lifallen27 分钟前
Paimon 与 ForSt 场景选型分析
java·大数据·flink
我登哥MVP30 分钟前
【Spring6笔记】 - 12 - 代理模式
java·spring boot·笔记·spring·代理模式·aop
潇洒畅想39 分钟前
1.2 希腊字母速查表 + 公式阅读实战
java·人工智能·python·算法·rust·云计算