Algorithm from entry to master series: insertion sort

I. Overview

We said in the previous section that sorting is part of the algorithm. So we learn sorting is also an introduction to the algorithm. In order to make everyone feel that sorting is part of the algorithm, I will give an example to prove it: For example, in a mahjong game, the opponent's cards need to be sorted after the cards are dealt. Think about it, mahjong sorting How to arrange it? What are its characteristics? And in the process of drawing cards and playing cards, we have to constantly sort them. How to sort? Which sorting algorithm is the fastest to choose?

In the above situation, we can analyze which sorting algorithm is more efficient. For example, the following picture already has a set of cards in a fixed order:

At this time it is our turn to draw the cards, the cards we draw are as follows:

At this time, to put this "three of the same" in the upper deck of cards, there are the following rules:

1. Normal "3 same" should be placed between "2 same" and "4 same".

2. It has nothing to do with cards of other suits, or even with "5 with". Just put "3 with" in the middle of "2 with" and "4 with". It doesn't matter where "2 with" and "4 with" are.

We learned about selection sorting. Is it appropriate to use selection sorting to sort the cards above? Obviously it is inappropriate, because the selection order must be compared from "70,000", the smallest card is selected to exchange positions with the first card, and so on. But here, the "3 of the same" of mahjong tiles has nothing to do with "70,000", and there is no need to affect "70,000". Therefore, it is not appropriate to use selective sort because of the high degree of time responsibility; it is better to use insertion sort here, what is insertion sort? That's what needs to be introduced in this section.

Two, insertion sort

Insertion sorting is a kind of simple sorting. The simple sorting is usually referred to simply because its algorithm is easier to understand, and does not mean that its use is simple. In order to let everyone master the insertion sort, we first look at the principle of insertion sort.

2.1, the principle of insertion sort

First, there is an array to be sorted as follows:

There is only one number 0 in the above array that needs to be arranged, and the other numbers are in the correct order. This kind of array is more efficient to use insertion sort. The following describes the process of using insertion sort for this array.

1. First compare 1 and 2, if 2 is smaller than 1, swap positions. Otherwise, the positions are not exchanged. This array does not need to swap positions.

2. Compare 2 and 3 again. If 3 is smaller than 2, swap positions. But the actual 3 is bigger than 2, so the position is not changed and remains unchanged.

3. In the same way, there is no need to switch positions when comparing 3 and 4, which remains unchanged

4. Next, compare 4 and 0, 0 is less than 4, so swap positions

The array after swapping positions is as follows:

5. Because the neighbor of 3 has changed, 3 and 0 are compared again, 0 is smaller than 3, and the positions are exchanged. The array after the exchange is as follows:

6. By analogy, the array after swapping positions of 0 and 2 is as follows:

The array of 0 and 1 swap positions is as follows:

The order of such an array is correct, but the loop has not been completed yet, because we just looped to the position of the number 4, and the number 5 has not been compared.

7. Finally compare 4 and 5. If 5 is smaller than 4, swap positions, but 5 is larger than 4, so the position remains unchanged. After the array is looped, the final sorting is as follows:

The above is the principle of insertion sort.

2.2, the difference between insertion sort and selection sort

For example, in the above example, insertion sort is to move 0 from index 4 to index 3, 2, 1, 0, and finally count as the end. The selection sort is to find the smallest value 0, and directly exchange with 1, the position from 0 to 1, and the position from 1 to 0. You can read the previous introduction about selection sorting.

Third, the code implementation of insertion sort

The following is the implementation of java code:

/**
 * 插入排序
 */
public static void algorithm5(){
 
    //原始数组
    int[] array={1,2,3,4,0,5};
    //数组的长度
    int length=array.length;
    //对数组进行遍历
    for (int i = 0; i < length; i++) {
        //第二个循环仅仅是将当前数据跟自己左边的数字进行比较,如果小于左边数字则交换位置,否则位置不变。
        for (int j = i; j > 0 && array[j]<array[j-1]; j--) {
                int temp = 0;
                temp = array[j-1];
                array[j-1]=array[j];
                array[j]=temp;
        }
    }
 
//将排好序的数组打印输出
    for (int i = 0; i < length; i++) {
        System.out.print(array[i]+",");
    }
} 

The above is the java code implementation of insertion sort. The second for loop in the code is the key point. The second for loop only compares the value on the left of the current data. If it is smaller than the value on the left, the position is exchanged, otherwise the position remains unchanged.

3.1 Time complexity of insertion sort

There are two kinds of time complexity for insertion sort:

1. When the array itself is ordered, such as {1, 2, 3, 4, 5}, the time complexity of using insertion sort is O(n). Reason: If the array itself is ordered, insertion sort needs to compare every two numbers next to each other, a total of N-1 times, so the time complexity is O(n).

2. When the array is unordered, it needs to compare (n^2)/2 times in the worst case, so the time complexity is O(n^2).

Four, summary

According to the time complexity of insertion sort, insertion sort is suitable for the following types of arrays:

1. Each element in the array is not far from its final position. For example {1,0,2,3,4,5}, the final position of 0 in this array should be the first position, and the position of 0 at this time is not far from the first position.

2. Incorporate a small array into an ordered large array. For example, a large ordered array {1,2,3,4,5,6} merges into a small array {0,1}.

3. The positions of only a few elements in the array are incorrect.

The above-mentioned three kinds of arrays are suitable for the insertion sort algorithm. The students who have played mahjong think about it, in the process of playing mahjong, the process of constantly drawing, playing, and sorting cards is not just one insertion sort!

Sorting is the basis of algorithms, and sorting has many uses. After reading the content of this section, you may wish to write a code to sort the cards you don't need to see which sorting algorithm is more suitable.

Guess you like

Origin blog.csdn.net/GUDUzhongliang/article/details/108730979