插入排序

工作原理:
  通过构建有序序列,对于未排序数据,在已排序序列中从后向前扫描,找到相应位置并插入。
时间复杂度:
  最差时间复杂度 | O(n^2)

代码:

复制代码
package com.core.test.sort;

public class InsertSort {
    public static void main(String[] args) {
        int[] a = {5, 1, 7, 3, 2, 8, 3, 4, 6};
        insertSort(a);
    }

    private static void insertSort(int[] arr) {
        /*
        * for循环相当于选中第一个元素作为已排序数据
        * 从第二个元素开始往已排序数据中插 i的值就是要插入已排序数据的值的坐标
        * */
        for (int i = 1; i < arr.length; i++) {
            if (arr[i] < arr[i - 1]) {
                int temp = arr[i];
                int j = i - 1;
                /*
                * 坐标i之前的数据是已经排好序的 找到一个不大于要插入的值的值 插入到他的后面即可
                * 在还没有找到之前 数据从前往后依次赋值 相当于给要插入的值挪位置了
                * */
                while (j >= 0 && arr[j] > temp) {
                    arr[j + 1] = arr[j];
                    j--;
                }
                arr[j + 1] = temp;
            }
        }
        for (int a : arr) {
            System.out.print(a + " ");
        }
    }
}
复制代码

 

posted on 2017-12-06 18:05  闲杂人等  阅读(114)  评论(0)    收藏  举报

编辑推荐:
· 2025年:是时候重新认识System.Text.Json了
· 源码浅析:SpringBoot main方法结束为什么程序不停止
· C#性能优化:为何 x * Math.Sqrt(x) 远胜 Math.Pow(x, 1.5)
· 本可避免的P1事故:Nginx变更导致网关请求均响应400
· 还在手写JSON调教大模型?.NET 9有新玩法
阅读排行:
· 2025年:是时候重新认识System.Text.Json了
· .NET 9 的免费午餐:GZip 性能提升38.3%
· 开源新旗舰 GLM-4.5:不想刷榜,只想干活儿
· 优雅的.net REST API之FastEndpoints
· .NET 10 中的新增功能系列文章1——运行时中的新增功能

导航

< 2025年7月 >
29 30 1 2 3 4 5
6 7 8 9 10 11 12
13 14 15 16 17 18 19
20 21 22 23 24 25 26
27 28 29 30 31 1 2
3 4 5 6 7 8 9

统计

点击右上角即可分享
微信分享提示