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

    基础排序参考
    https://blog.csdn.net/yushiyi6453/article/details/76407640

    插入排序

    插入排序从小到大排序:首先位置1上的数和位置0上的数进行比较,如果位置1上的数大于位置0上的数,将位置0上的数向后移一位,将1插入到0位置,否则不处理。位置k上的数和之前的数依次进行比较,如果位置K上的数更大,将之前的数向后移位,最后将位置k上的数插入不满足条件点,反之不处理。

    package insertsort;

    import java.util.Scanner;

    /**
     * @author WangXiaoeZhe
     * @Date: Created in 2019/11/21 16:17
     * @description:
     */

    public class InsertSort {
        /**
         * 插入排序
         *
         * @param args
         */

        public static void main(String[] args) {
            Scanner scanner = new Scanner(System.in);
            int[] arr = new int[5];
            for (int i = 0; i < arr.length; i++) {
                arr[i] = scanner.nextInt();
            }
            int[] ints = insertSort(arr);
            for (int i = 0; i < ints.length; i++) {
                System.out.println(arr[i]);
            }
        }

        private static int[] insertSort(int[] arr) {
            for (int i = 1; i < arr.length; i++) {
                for (int j = i - 1; j >= 0 && arr[j] > arr[j + 1]; j--) {
                    swap(arr,j,j+1);
                }
            }
            return arr;
        }

        public static void swap(int[] arr, int i, int j) {
            int tmp = arr[i];
            arr[i] = arr[j];
            arr[j] = tmp;
        }


    }

    平均时间复杂度: O(n^2) 最坏时间复杂度:O(n^2) 空间复杂度: O(1) 不稳定

  • 相关阅读:
    Centos安装webbench
    schema://host[:port#]/path/.../[?query-string][#anchor]
    ab压力测试报错: apr_socket_recv: Connection reset by peer (104)
    Nginx配置proxy_pass转发的/路径问题
    压力测试的轻量级具体做法
    jquery删除动态增加的li
    css如何li中选中后加上class属性js控制
    JQuery中两个ul标签的li互相移动实现方法
    xcode生成的IOS安装文件的位置
    xcode生成文件路径
  • 原文地址:https://www.cnblogs.com/wuhen8866/p/11906420.html
Copyright © 2011-2022 走看看