• 插入排序


    1.直接插入排序

    插入排序就是每一步都将一个待排数据按其大小插入到已经排序的数据中的适当位置,直到全部插入完毕。
    插入排序的工作方式像玩扑克牌时顺序放牌一样。开始时,左手为空并且桌子上的牌面向下。然后,每次从桌上拿一张牌并将它插入左手中正确的位置。为了找到正确的位置,我们从右到左将它与已在手中的每张牌比较,原来的牌是排好序的,如果比刚拿出的牌大,则将其再向右移一个位置,直到找到一个比刚拿出来的牌更小的,此时将这张牌放到该位置。
    算法适用于少量数据的排序,时间复杂度为O(n^2)。是稳定的排序方法,即两个相等的元素在排序后能保持原来的顺序。
    其算法如下:

        sort(a)
            for i = 1 to a.length
                temp = a[i]
                i = j
                while j > 0 and a[j - 1] > temp
                    a[j] = a[j-1]
                    j--
                a[j] = temp

    java实现

    package com.diysoul.algorithm.sort;
    
    import java.util.Random;
    
    public class InsertionSort {
    
        public static void sort(int[] a) {
            int length = a.length;
            for (int i = 1; i < length; i++) {
                int temp = a[i];
                int j = i;
                while (j > 0 && a[j - 1] > temp) {
                    a[j] = a[j - 1];
                    j--;
                }
                a[j] = temp;
            }
        }
    
        public static void main(String[] args) {
            int maxSize = 100;
            int min = 0;
            int max = 1000;
            Random random = new Random();
    
            int[] a = new int[maxSize];
            for (int i = 0; i < a.length; i++) {
                a[i] = random.nextInt(max - min) + min;
            }
            print(a);
            sort(a);
            print(a);
            checkSort(a);
        }
    
        private static void checkSort(int[] array) {
            if (array == null || array.length == 0)
                return;
            for (int i = 1; i < array.length; i++) {
                if (array[i - 1] > array[i]) {
                    System.out.println("Error! Array is not sorted in index " + i);
                    break;
                }
            }
        }
    
        private static void print(int[] array) {
            if (array == null || array.length == 0)
                return;
            System.out.print("insertion sort array(" + array.length + "): ");
            int i = 0;
            for (; i < array.length - 1; i++) {
                System.out.print(array[i] + ", ");
            }
            System.out.println(array[i]);
        }
    }
  • 相关阅读:
    Difference Between Performance Testing, Load Testing and Stress Testing
    什么是测试策略?
    性能测试和压力测试的区别
    测试工程师培训体系
    Java测试工具
    浅谈HTTP中Get与Post的区别
    Python 读书系列
    Automation- watin
    脚本语言&& Performance Testing
    HDFS分布式集群安装
  • 原文地址:https://www.cnblogs.com/diysoul/p/5672037.html
Copyright © 2020-2023  润新知