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

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

相关推荐
我是苏苏2 小时前
C#高级:程序查询写法性能优化提升策略(附带Gzip算法示例)
开发语言·算法·c#
木木子99992 小时前
业务架构、应用架构、数据架构、技术架构
java·开发语言·架构
sali-tec3 小时前
C# 基于halcon的视觉工作流-章56-彩图转云图
人工智能·算法·计算机视觉·c#
qq_5470261794 小时前
Flowable 工作流引擎
java·服务器·前端
鼓掌MVP5 小时前
Java框架的发展历程体现了软件工程思想的持续进化
java·spring·架构
编程爱好者熊浪5 小时前
两次连接池泄露的BUG
java·数据库
lllsure5 小时前
【Spring Cloud】Spring Cloud Config
java·spring·spring cloud
鬼火儿6 小时前
SpringBoot】Spring Boot 项目的打包配置
java·后端
NON-JUDGMENTAL6 小时前
Tomcat 新手避坑指南:环境配置 + 启动问题 + 乱码解决全流程
java·tomcat
黑岚樱梦6 小时前
代码随想录打卡day23:435.无重叠区间
算法