? Direct Insert sort (straight insertion sort)

Source: Internet
Author: User

1. Definition

The basic operation of a direct insert sort (straight insertion sort) is to insert a record into an ordered table that is already sorted, resulting in a new, sequential table with a 1 increase in the number of records.

The basic idea of inserting a sort (insertion sort) is to insert a record to be sorted each time, by its keyword size, into the appropriate location in the previously sorted sub-file until all records are inserted.

2. Basic Ideas(1), basic ideas

Suppose that the records to be sorted are stored in the array R[1..N]. Initially, r[1] self into 1 ordered areas, unordered area is R[2..N]. From i=2 up to i=n, sequentially insert r[i] into the current ordered area R[1..i-1], generating an ordered area with N Records.

(2), section i-1 Direct insertion Sort

Usually a record r[i] (i=2,3,...,n-1) is inserted into the current ordered area, making it still guaranteed that the records in that interval are sorted by the order of the keywords i-1 direct insertion.

At some intermediate moment of the sort process, R is divided into two sub-intervals r[1. I-1] (ordered order area) and r[i. N] (the currently unsorted part, which can be called an unordered area).

The basic operation of a direct insert sort is to interpolate the 1th record of the current unordered zone R[i] to the ordered area r[1. I-1] in the appropriate position, so that r[1. I] into a new ordered area. Because this method adds a record to the ordered area each time, it is usually called the increment method.

The insertion sort is very similar to the cards that are organized on hand when playing poker. The 1th card to be touched does not need to be sorted out, and each time thereafter the top 1 is touched at the right position in the left hand (ordered area) from the card on the table (unordered area). In order to find this correct position, you must compare the hand that is touched with the cards already in the left-to-right (or from right to left).

3, a trip direct insertion sorting method(1), simple method

First find the correct insertion position K (1≤k≤i-1) of R[i] in the current ordered area R[1..i-1], and then r[k. The records in I-1] move back one position, freeing up space on the K position to insert r[i].

Attention:

If r[i] has a keyword greater than or equal to r[1. I-1], then r[i] is inserted in the original position.

(2), improvement method

An alternate way to find comparison operations and record move operations.

Specific practices:

The keywords to insert record r[i] are compared from right to left with the keywords in the ordered area record R[j] (j=i-1,i-2,...,1):

① if the keyword of r[j] is greater than r[i], then the r[j] is shifted back one position;

② if the keyword of r[j] is less than or equal to R[i], then the find process ends and j+1 is the insertion position of r[i].

The key is larger than the r[i] key word has been moved, so the j+1 position has been vacated, as long as the r[i] directly into this location to complete a direct insertion of the sort.

4. Direct Insertion Sorting algorithm(1), Algorithm description
/* To order table L do a direct insert sort */void insertsort (sqlist *l) {    int i,j;    for (i=2;i<=l->length;i++)        /*i starting from 2, we assume that data[1] has been put in place, the next number is actually the problem of inserting it to the left or right side of it *       /{if (l-> DATA[I]<L->DATA[I+1]//    * L->data[i] must be inserted into the ordered sub-table */       {           l->data[0]=l->data[i];    /* Set Sentinel *           /for (j=i-1; l->data[j]>l->data[0];j--)               l->data[j+1]=l->data[j];    /* Log back */           l->data[j+1]=l->data[0];        /* Insert to the correct location */       }}     }

You can also use the following methods:

R[1..N for records in sequential table R] by ascending order void Lnsertsort (Seqlist r) {    int i,j; for   (i=2;i<=n;i++)       //Insert r[2],...,r[ N]   if (r[i].key<r[i-1].key)  //If R[i].key is greater than or equal to all keys in the ordered area, then R[i] shall be in the original position   {       r[0]=r[i];j=i-1;     R[0] is the Sentinel, and is a copy of r[i] do       {                                    r[j+1]=r[j];    //right-to-left in the ordered area r[1. I-1] In the insertion position of find r[i], the key is greater than the r[i].key of the record is moved                j--;       } while       (R[0].key<r[j].key);//when R[i].key≥r[j].key is terminated       r[j+1]=r[0];             //r[i] insert to the correct position   }}
(2), the role of Sentinel

Additional records introduced in the algorithm r[0] are called Sentinel or Sentinel.

Sentinel has two functions:

① a copy of the R[i] before the search (insertion position) loop, so that the contents of r[i] are not lost due to the post-move of the record;

② Its main function is to "monitor" the subscript variable J in the lookup loop. Once crossed out (that is, j=0), because the R[0].key and their own comparison, the loop to determine the condition is not established so that the end of the search cycle, so as to avoid every time within the loop to detect whether J is out of bounds (that is, the loop to determine the condition "j>=1").

Attention:

① in fact, all additional nodes (elements) that are introduced to simplify boundary conditions can be called Sentinels.

"Example" the head node in a single linked list is actually a Sentinel.

The ② introduces a sentinel, which reduces the time it takes to find the loop condition by about half, so the amount of time saved on a file with a large number of records is considerable. For an algorithm that is similar to sorting in such a way that it can be used very frequently, reduce its run time as much as possible. Therefore, we should not consider the Sentinels in the above algorithm as tricks, but should understand and grasp this technique deeply.

5. Algorithm Analysis(1), the time performance analysis of the algorithm

For files with N records, a n-1 is ordered.

Time complexity in various states:

┌─────────┬─────┬──────┬──────┐

│ Initial file Status │ positive order │ reverse order │ unordered (average) │

├─────────┼─────┼──────┼──────┤

│ Key │1│i+1│ (i-2) of the first trip/2│

│ Word comparison number ││││

├─────────┼─────┼──────┼──────┤

│ Total keyword Comparisons │n-1│ (n+2) (n-1)/2│≈n2/4│

├─────────┼─────┼──────┼──────┤

│ I trip record number of moves │0│i+2│ (i-2)/2│

├─────────┼─────┼──────┼──────┤

│ total number of records moved │0│ (n-1) (n+4)/2│≈n2/4│

├─────────┼─────┼──────┼──────┤

│ Time complexity │0 (n) │o (n2) │o (n2) │

└─────────┴─────┴──────┴──────┘

Attention:

The initial file is incrementally ordered by keyword, or "positive order".

Initial file descending order by keyword, abbreviated as "reverse order".

(2) Spatial complexity analysis of algorithm

The auxiliary space required by the algorithm is a lookout , auxiliary space complexity s (n) =o (1). is an in- place sort .

(3) Stability of direct insertion sequencing

The direct insert sort is a stable sorting method.

? Direct Insert sort (straight insertion sort)

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.