Data structure-Direct insertion Sort method

Source: Internet
Author: User
data Structure-Direct insertion sort method.

The previous blog has introduced the bubble sort method
and simple choice sorting method.

In fact, the above two basic ideas are the same, that is, through the two-tier cycle, in every 1 internal loops to find 1 unordered extremum elements, and then move this element to the forefront of the array.

But the basic idea of the direct insertion sort method introduced in this article is different from the sorting method above, and it can be said that the algorithm of directly inserting the sort method is more direct to the human brain. Basic Ideas An example

Let's say we have a few cards in front of us.

|1|2|3|7|6|5|9|8|

To let you move the position of the card, so that these cards from childhood to rearrange.

Let's simulate your brain behavior ...

First of all, we can see that the front of the |1|2|3| is orderly, do not need to compare and move.

Second, we are not going to consider which of the remaining unsorted cards is the smallest one.

But to observe, eh. Find 6:7 Big nests ~

Just go ahead and put the card 6 in front of 7, and the card becomes this:

|1|2|3|6|7|5|9|8|

Then continue, and found 5:7 small, put 5 in front, put in front of which card, intuitively we will feel 6:5, so put in 6 before:

|1|2|3|5|6|7|9|8|

Next, we found 9:7 big ... Instead of moving, move the back 8 to the 9 front.

|1|2|3|5|6|7|8| 9|

Well, just a few steps to complete the order, is not that our brain is very strong. Thinking Analysis

But if we're going to use code to simulate our brain's algorithm, we need to know every 1 steps of the algorithm. 1. Identify the cards to start the comparison

First of all, we skipped the 1 2 3 3 cards from the beginning and went straight to compare the two cards 7 and 5 in the back.
It's because we think the 123 in front of us is already well sequenced.

But is there a number of sorted elements that precede the sorting method's predecessor?

No

If we remove the card 123, it becomes the following:

|7|6|5|9|8|

Still can use this idea to sort. Because we can be the 1th element 7, think of it as 1 queues that are already sorted.

So the actual comparison starts with the second card in the queue, 6.

That is to say, in this idea, if there is an array of arr[n], compare from the second element arr[1] 2. Compared to who?

Next continue to say, we take the card 6来 compare, with who compares, is with 6 before the card 7来 comparison.

That is, if the element we are comparing is arr[i], then it will be compared to the element arr[i-1 in front of it. 3. If Arr[i] is larger than arr[i-1]

To make it easier to describe, we change the array to the following state

|1|2|3|6|7|5|9|8|

We are comparing the element is 7, found that 7:6 small case, is not moving any position of the card, but to compare the card 5.

That is, if arr[i] > arr[i-1], direct i++ to the next card 4. Conversely, if arr[i] is smaller than arr[i-1

Now we're comparing 5 and 7 of its previous position.

|1|2|3|6|7|5|9|8|

In this case, you will change the position of the element.
We will put the card 5 forward, but where it, and how to put it. and continue to analyze 5. First, take out the cards you want to move forward.

That's how the queue becomes.

|1|2|3|6|7|*|9|8|

|5| 6. The next 11 positions in front of the cards.

In fact, 5 of the front 6 and 7 have to move back one position, why 3 do not move it, because 3:5 small ah

Two-step (actually 1 loops)

|1|2|3|6|7|*|9|8| ==>

|1|2|3|6|*|7|9|8| ==>

|1|2|3|*|6|7|9|8| 7. Put the cards back.

|1|2|3|5|6|7|9|8| 8. Continue to compare the next card

|1|2|3|5|6|7|9|8| 9. Summary

As you can see, this algorithm still has two loops.

The outer loop is used to compare elements and its first 1 elements.

The inner loop actually moves 1 child queues. Code Implementation

After understanding the idea, it is not difficult to write the code in C language.

int straightinsertionsort (int * arr, int len) {
    int i, J;
    int tmp = 0;
    for (int i = 1; i < Len; i++) {
        if (Arr[i-1] > Arr[i]) {//1. The element'll be moved only if it's smaller then The previous one
                                //2. The element only would be moved forward.
            TMP = Arr[i]; Use a variable to store the element which'll be moved.
            j = i-1;
            Do {
                arr[j + 1] = Arr[j];         Move the previous element one position backward fisrt;
                j--;
            }
            while (J >= 0 && arr[j] > tmp);  The elements after the new position of the moving element move!

            Arr[j + 1] = tmp;                Put the moving element to the new position
        } and return
    0;
}
Debug Information

Let's take a look at the debug information

4, 1, 5, 8, 0, 3, 7, 9, 6, 2 *1, 4, 5, 8, 0, 3, 7, 9, 6, 2 *0, 1, 4, 5, 8, 3, 7, 9, 6, 2 0, 1,
*3, 4, 5, 8, 7, 9, 6, 2
0, 1, 3, 4, 5, *7, 8, 9, 6, 2, 0, 1, 3, 4, *6, 5, 7, 8, 9 2, 0, *2, 1, 3, 4,
5, 6, 7, 8 change
count:25
Compare count:22
0, 1, 2, 3, 4, 5, 6, 7, 8, 9

You can see how the elements are moved.
This algorithm compares 20 times, the position moves 25 times

First of all, this algorithm is relatively few times, the same array, with the bubble sort of comparison is 39, and the simple choice of the number of comparisons is 45.

Position move is 25, with bubble still more?

No, the bubbling position change is actually an element exchange (moving two elements), and the location change here is really a change in the position of the 1 elements.

It can be seen that the direct insertion selection method is more efficient than the bubble sort method.
In fact, the time complexity analysis is better than the simple selection method .

First of all, the best case is already sorted, only need to compare n times, no element movement, time complexity is O (n)

But the worst case scenario

Is that the array itself is sorted in reverse order, for example

|5|4|3|2|1|

So, the number of comparisons is
∑i=1n−1i=1+2+3+4+...+n−1=n (n−1) 2 \sum\limits_{i=1}^{n-1}i= 1 + 2 + 3 + 4 + ... + n-1 = \frac{n (n-1)}{2}

The number of moves is
∑i=2n−1i=2+3+4+...+n=n (n+2) 2 \sum\limits_{i=2}^{n-1}i= 2 + 3 + 4 + ... + n = \frac{n (n+2)}{2}

Time complexity is still O (n2) O (n^2) Oh. Summary

We've also learned about 1 more efficient sorting methods.

The key is that the idea of a direct insertion sort is more in line with human brain habits.

As you can see, the algorithms that are easy to write (double sorting) are not necessarily the most intuitive algorithms in the human brain.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.