zoukankan      html  css  js  c++  java
  • 插入排序

    工作原理:
      通过构建有序序列,对于未排序数据,在已排序序列中从后向前扫描,找到相应位置并插入。
    时间复杂度:
      最差时间复杂度 | 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 + " ");
            }
        }
    }
  • 相关阅读:
    大小端模式
    深入理解c/c++ 内存对齐
    示波器使用
    C结构体
    51单片机内存问题
    S5PV210启动过程详解1
    程序中内存从哪里来
    再论typedef
    ARM体系结构总结
    MMU实验实验
  • 原文地址:https://www.cnblogs.com/programmer1/p/7994106.html
Copyright © 2011-2022 走看看