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

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

相关推荐
daidaidaiyu4 小时前
一文学习 工作流开发 BPMN、 Flowable
java
2401_891482175 小时前
多平台UI框架C++开发
开发语言·c++·算法
SuniaWang5 小时前
《Spring AI + 大模型全栈实战》学习手册系列 · 专题六:《Vue3 前端开发实战:打造企业级 RAG 问答界面》
java·前端·人工智能·spring boot·后端·spring·架构
sheji34165 小时前
【开题答辩全过程】以 基于springboot的扶贫系统为例,包含答辩的问题和答案
java·spring boot·后端
88号技师5 小时前
2026年3月中科院一区SCI-贝塞尔曲线优化算法Bezier curve-based optimization-附Matlab免费代码
开发语言·算法·matlab·优化算法
t198751285 小时前
三维点云最小二乘拟合MATLAB程序
开发语言·算法·matlab
m0_726965986 小时前
面面面,面面(1)
java·开发语言
x_xbx6 小时前
LeetCode:148. 排序链表
算法·leetcode·链表
Darkwanderor6 小时前
三分算法的简单应用
c++·算法·三分法·三分算法
2401_831920746 小时前
分布式系统安全通信
开发语言·c++·算法