[5] based sort, insertion sort - Insertion Sort

Insertion sort - Insertion Sort

Record -bobo simple algorithm teacher Fun Series - Fun algorithm - sort foundation

Insertion Sort Insertion Sort

Compare inserted

Insertion sort design ideas

Insertion sort the number of columns is divided into and "unsorted" in two parts, each selected from the elements of "unsorted" one inserted in the correct position of the element "sorted" in, so iteration until all of the elements "sorted" orderly.

The first number of array generally considered to be an ordered array, the first number is not required to consider already lined up, you do not need to be inserted into the front. Scanned from the back of the ordered array, the array number of the remaining n-1, depending on the size of the value is inserted into the ordered array, until all the numbers in the array is an ordered array so far. N elements, then it needs to be sorted n-1 times! Compare inserted.

For example: 1234 for descending sort

First trip

1 2 3 4

Scanning an ordered array from the back, and the second number 2 ordered array compared 1, 2 larger than 1, a shift to a position, just at this time is scanned so that the ordered array of number, the result is inserted in front of the 2 1, to give 2,1 new sequence;

2 1 3 4

Second trip

2 1 3 4

3 starts, 3 is greater than 1, after one shift a position, that is, both to exchange position

2 3 1 4

3 is larger than 2, 2 a shift position.

3 2 1 4

Third trip

3 2 1 4

4 starts, 4 greater than 1, after a position shifted 1

3 2 4 1

4 greater than 2, a position shifted after 2

3 4 2 1

4 greater than 3, 3 move, than over

4 3 2 1

Insertion sort code implementation

InsertionSort

package algo;

import java.util.*;

public class InsertionSort{

    // 我们的算法类不允许产生任何实例
    private InsertionSort(){}

    public static void sort(Comparable[] arr){

        int n = arr.length;
        for (int i = 0; i < n; i++) {

            // 寻找元素arr[i]合适的插入位置

            // 写法1
            // 比较  当前与它的前一个  小于的话就交换  大的话就中止这一趟
            // 插入排序比选择  第二个循环比较 提前中止   理论上插入比选择快点 但是...实际上为什么更慢呢?下一节介绍可以改进吧 
       
//            for( int j = i ; j > 0 ; j -- )
//                if( arr[j].compareTo( arr[j-1] ) < 0 )
//                    swap( arr, j , j-1 );
//                else
//                    break;

            // 写法2
            //同时满足两个 j > 0   小于的话就一直交换  一旦大于就中止 下一个数进行比较
            for( int j = i; j > 0 && arr[j].compareTo(arr[j-1]) < 0 ; j--)
                swap(arr, j, j-1);

        }
    }

    private static void swap(Object[] arr, int i, int j) {
        Object t = arr[i];
        arr[i] = arr[j];
        arr[j] = t;
    }

    // 测试InsertionSort
    public static void main(String[] args) {

        int N = 200;
        Integer[] arr = SortTestHelper.generateRandomArray(N, 0, 10000);
        SortTestHelper.testSort("algo.InsertionSort", arr);

        return;
    }
}

SortTestHelper.java

package algo;

import java.lang.reflect.Method;
import java.lang.Class;

public class SortTestHelper {

    // SortTestHelper不允许产生任何实例
    private SortTestHelper(){}

    // 生成有n个元素的随机数组,每个元素的随机范围为[rangeL, rangeR]
    public static Integer[] generateRandomArray(int n, int rangeL, int rangeR) {

        assert rangeL <= rangeR;

        Integer[] arr = new Integer[n];

        for (int i = 0; i < n; i++)
            arr[i] = new Integer((int)(Math.random() * (rangeR - rangeL + 1) + rangeL));
        return arr;
    }

    // 打印arr数组的所有内容
    public static void printArray(Object[] arr) {

        for (int i = 0; i < arr.length; i++){
            System.out.print( arr[i] );
            System.out.print( ' ' );
        }
        System.out.println();

        return;
    }

    // 判断arr数组是否有序
    public static boolean isSorted(Comparable[] arr){

        for( int i = 0 ; i < arr.length - 1 ; i ++ )
            if( arr[i].compareTo(arr[i+1]) > 0 )
                return false;
        return true;
    }

    // 测试sortClassName所对应的排序算法排序arr数组所得到结果的正确性和算法运行时间
    public static void testSort(String sortClassName, Comparable[] arr){

        // 通过Java的反射机制,通过排序的类名,运行排序函数
        try{
            // 通过sortClassName获得排序函数的Class对象
            Class sortClass = Class.forName(sortClassName);
            // 通过排序函数的Class对象获得排序方法
            Method sortMethod = sortClass.getMethod("sort",new Class[]{Comparable[].class});
            // 排序参数只有一个,是可比较数组arr
            Object[] params = new Object[]{arr};

            long startTime = System.currentTimeMillis();
            // 调用排序函数
            sortMethod.invoke(null,params);
            long endTime = System.currentTimeMillis();

            assert isSorted( arr );

            System.out.println( sortClass.getSimpleName()+ " : " + (endTime-startTime) + "ms" );
        }
        catch(Exception e){
            e.printStackTrace();
        }
    }
}

Result Test InsertionSort

D:\Environments\jdk-11.0.2\bin\java.exe -javaagent:D:\Java\ideaIU-2019.2.win\lib\idea_rt.jar=7391:D:\Java\ideaIU-2019.2.win\bin -Dfile.encoding=UTF-8 -classpath D:\IdeaProjects\imooc\Play-with-Algorithms\02-Sorting-Basic\out\production\05-Insertion-Sort algo.InsertionSort
InsertionSort : 2ms
48 68 73 256 393 415 512 520 521 549 558 613 618 650 707 709 720 755 813 830 841 853 856 894 1017 1061 1092 1199 1212 1227 1374 1421 1454 1535 1552 1584 1601 1617 1652 1758 1907 1979 1998 2081 2103 2107 2157 2246 2271 2274 2312 2319 2365 2418 2449 2509 2565 2569 2629 2668 2741 2793 2927 2950 2956 3105 3140 3166 3209 3287 3364 3403 3407 3427 3469 3573 3645 3835 3887 3902 3919 4045 4071 4122 4225 4300 4355 4364 4378 4412 4505 4516 4523 4533 4546 4636 4650 4678 4776 4780 4821 4911 5010 5174 5204 5220 5231 5426 5473 5484 5645 5827 5884 5887 5902 5939 6012 6031 6063 6174 6210 6334 6337 6358 6358 6367 6405 6412 6448 6639 6678 6838 6991 7002 7148 7189 7327 7357 7400 7429 7519 7522 7559 7634 7733 7841 7945 7960 8013 8116 8139 8193 8203 8214 8222 8234 8243 8248 8258 8273 8309 8357 8452 8569 8586 8662 8687 8740 8842 8853 8863 8891 8907 8930 8950 9011 9086 9148 9239 9251 9286 9321 9346 9392 9434 9491 9518 9537 9589 9601 9675 9766 9801 9825 9837 9882 9883 9884 9915 9962 

Process finished with exit code 0

: Insert Compare Sort sorting and selection

Main

package algo;

import java.util.Arrays;

public class Main {

    // 比较SelectionSort和InsertionSort两种排序算法的性能效率
    // 此时,插入排序比选择排序性能略低
    public static void main(String[] args) {

        int N = 200000;//20万个数排序
        System.out.println("Test for random array, size = " + N + " , random range [0, " + N + "]");

        Integer[] arr1 = SortTestHelper.generateRandomArray(N, 0, N);
        Integer[] arr2 = Arrays.copyOf(arr1, arr1.length);//拷贝数组

        SortTestHelper.testSort("algo.SelectionSort", arr1);
        SortTestHelper.testSort("algo.InsertionSort", arr2);

        return;
    }
}

Select insertion sort a large set of performance data point not very slow and very slow

Comparison of the exchange too many times

Result

D:\Environments\jdk-11.0.2\bin\java.exe -javaagent:D:\Java\ideaIU-2019.2.win\lib\idea_rt.jar=7405:D:\Java\ideaIU-2019.2.win\bin -Dfile.encoding=UTF-8 -classpath D:\IdeaProjects\imooc\Play-with-Algorithms\02-Sorting-Basic\out\production\05-Insertion-Sort algo.Main
Test for random array, size = 200000 , random range [0, 200000]
SelectionSort : 87513ms
InsertionSort : 335960ms

Process finished with exit code 0

Published 78 original articles · won praise 10 · views 10000 +

Guess you like

Origin blog.csdn.net/qq_41569732/article/details/104270213