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

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

相关推荐
WiChP6 小时前
【V0.1B5】从零开始的2D游戏引擎开发之路
java·服务器·数据库
cch89186 小时前
汇编与Java:底层与高层的编程对决
java·开发语言·汇编
荒川之神7 小时前
拉链表概念与基本设计
java·开发语言·数据库
cch89187 小时前
汇编与Go:底层到高层的编程差异
java·汇编·golang
workflower7 小时前
用硬件换时间”与“用算法降成本”之间的博弈
人工智能·算法·安全·集成测试·无人机·ai编程
chushiyunen7 小时前
python中的@Property和@Setter
java·开发语言·python
禾小西7 小时前
Java中使用正则表达式核心解析
java·python·正则表达式
yoyo_zzm7 小时前
JAVA (Springboot) i18n国际化语言配置
java·spring boot·python