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;
        }
    }
}

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

相关推荐
wand codemonkey25 分钟前
SpringbootWeb【入门】+MySQL【安装】+【DataDrip安装 】+【连接MySQL】
java·mysql·mybatis
Mahir088 小时前
Spring 循环依赖深度解密:从问题本质到三级缓存源码级解析
java·后端·spring·缓存·面试·循环依赖·三级缓存
RyFit9 小时前
SpringAI 常见问题及解决方案大全
java·ai
石山代码10 小时前
C++ 内存分区 堆区
java·开发语言·c++
心中有国也有家10 小时前
cann-recipes-infer:昇腾 NPU 推理的“菜谱集合”
经验分享·笔记·学习·算法
绝知此事10 小时前
【算法突围 01】线性结构与哈希表:后端开发的收纳术
java·数据结构·算法·面试·jdk·散列表
无风听海10 小时前
C# 隐式转换深度解析
java·开发语言·c#
碧海银沙音频科技研究院10 小时前
通话AEC与语音识别AEC的软硬回采链路
深度学习·算法·语音识别
一只大袋鼠11 小时前
Git 进阶(二):分支管理、暂存栈、远程仓库与多人协作
java·开发语言·git
csdn_aspnet11 小时前
Python 算法快闪 LeetCode 编号 70 - 爬楼梯
python·算法·leetcode·职场和发展