Data Structure-sort: insert sort (direct insert sort)

Source: Internet
Author: User
The basic idea of insertion sort is to insert a record to be sorted into the appropriate position of the subfile in the preceding sorted order according to its keyword size, until all records are inserted.
This section describes two insertion sorting methods: Direct insertion sorting and Hill sorting.
1. Basic Idea of directly inserting sorting
The basic idea of directly inserting a sort insertion sorting is to regard n elements to be sorted as an ordered table and an unordered table. At the beginning, an ordered table contains only one element, an unordered table contains n-1 elements. During the sorting process, the first element is extracted from the unordered table and inserted to the appropriate position in the ordered table to form a new ordered table, repeat n-1 times to complete the sorting process.
Insert a [I] to a [0], a [1],..., the specific implementation process in a [I-1] is: first assign a [I] to the variable t, then t with a [I-1], a [I-2],... for comparison, move the element greater than T to the right until a J (0 <= j <= i-1) is found ), if a [J] <= T or J is (-1), assign t to a [J + 1].

2, The I-1 directly inserted sort:
Generally, a record R [I] (I = 2, 3 ,..., N-1) insert to the current ordered area, so that after insertion, the records in the range are still guaranteed to be sorted by the keyword ordered operation called the I-1 directly insert sort.
During a certain period of time in the sorting process, R is divided into two subintervals R [1 .. i-1] (sorted order area) and R [I .. n] (unordered section, which can be called unordered area ).
The basic operation of directly inserting sorting records is to insert the 1st records of the current unordered partition into the ordered partition R [1 .. i-1] in the appropriate position to make R [1 .. i] into a new ordered area. This method adds one record to the ordered area at a time, which is usually called the increment method.
The insertion sorting is very similar to the cards in poker. You do not need to sort out the 1st cards you have touched. After that, you can touch the top 1 card from the card (unordered area) on the table and insert it to the correct position in the left-hand card (ordered area. In order to find the correct position, you must compare the selected cards from left to right (or from right to left) with the ones in the left hand.

Insert sorting method directly

1. Simple Method

First in the current ordered zone R [1 .. find the correct Insertion Location K for R [I] in I-1] (1 ≤ k ≤ i-1); then place R [k .. all records in I-1] Move one location behind, freeing up space on K locations to insert R [I].
Note:
If the keyword of R [I] is greater than or equal to the keyword of all records in R [1 .. I-1], R [I] is inserted to the original location.

2. Improvement Methods
A method that allows you to search for comparison operations and record moving operations in turn.
Specific Practices:
Record the keywords of the record R [I] from right to left and record R [J] (j = I-1, I-2 ,..., 1) keyword comparison:
① If the keyword of R [J] is greater than the keyword of R [I], the R [J] is moved back to a position;
② If the keyword of R [J] is less than or equal to the keyword of R [I], the search process ends, and J + 1 is the insert position of R [I.
Records with larger keywords than those of R [I] have been moved backward, so the position of J + 1 has been vacated, you only need to insert R [I] directly to this position to complete the sort of insertion directly.

Insert sorting algorithm directly

1. Algorithm Description

 

Using system;
Using system. Collections. Generic;
Using system. text;

Namespace exinsertionsorter
{
Public class insertionsorter
{
Public void sort (INT [] ARR)
{
For (INT I = 1; I <arr. length; I ++)
{
Int T = arr [I];
Int J = I;
While (j> 0) & (ARR [J-1]> T ))
{
Arr [J] = arr [J-1]; // Exchange Order
-- J;
}
Arr [J] = T;
}
}
Static void main (string [] ARGs)
{
Int [] array = new int [] {1, 5, 3, 6, 10, 55, 9, 2, 87, 12, 34, 75, 33, 47 };
Insertionsorter I = new insertionsorter ();
I. Sort (array );
Foreach (INT m in array)
Console. writeline ("{0}", M );
}
}
}

4. Efficiency Analysis of direct insertion sorting
(1) time complexity
From the time analysis, the outer loop needs to be inserted n-1 times. Each insert operation must be at least one time (in the forward direction) and moved twice. At most, the insert operation can be compared to I, And I + 2 times (in the reverse direction) (I = 1, 2 ,..., N-1 ). If Cmin, Cmax, and cave are used to represent the minimum, maximum, and average values of the total number of comparisons of an element, mmin, mMax and Mave indicate the minimum, maximum, and average values of the total number of moving elements. The values corresponding to the preceding direct Insertion Algorithm are:
Cmin = n-1 mmin = 2 (n-1)
Cmax = 1 + 2 +... + N-1 = (n2-n)/2 mMax = 3 + 4 +... + N + 1 = (n2 + 3n-4)/2
Cave = (n2 + N-2)/4 mMax = (n2 + 7n-8)/4
Therefore, the time complexity of directly inserting sorting is O (n2 ).

From the analysis of time complexity, we can see that when the elements to be sorted are sorted in ascending or descending order, the number of comparisons and movements are less; when the sorted elements are sorted in descending or descending order, the number of comparisons and moves are large, therefore, insertion sorting is more suitable for the basic order (positive order) of raw data.

Although the insertion method is complex as O (n2) in the worst case, the insertion sorting method is a fast sorting method for small-scale input. Many complex sorting methods, such as quick sorting, are used for sorting when the scale is small.

(2) spatial complexity
First of all, from the perspective of space, it only needs the auxiliary space of one element, used for element location interchange O (1)

(3) stability:
Insert sorting is stable, because elements with the same value must be inserted after the element with the same value, that is, the relative order remains unchanged.

(4) Structure Complexity and Applicability

Insert sorting is a simple sorting method. It not only applies to the sequential storage structure (array), but also applies to the link storage structure. However, when directly inserting and sorting on the Link storage structure, instead of moving the position of the element, modify the corresponding pointer.

 

2. Role of sentinel
The additional record R [0] introduced in the algorithm is called the Sentinel ).
The Sentinel has two functions:
① Before the person finds (Insert Location) the loop, it saves a copy of R [I], so that the content of R [I] is not lost due to record move;
② Its main function is to "Monitor" subscripts in the search loop to determine whether the variable J has crossed the border. Once the cross-border (j = 0) is exceeded, because R [0]. the key is compared with its own, and the cycle judgment condition is not true, so that the search cycle ends, this avoids checking whether J exceeded each time in the cycle (that is, omitting the criterion "j> = 1 ").
Note:
① In fact, any additional node (element) introduced to simplify the boundary condition can be called a sentinel.
[Example] the header node in a single-chain table is actually a sentinel.
② The introduction of the Sentel reduces the time required to test the cyclic conditions by about half. Therefore, saving a considerable amount of time for files with a large number of records. For algorithms that are frequently used, such as sorting, the running time should be minimized. Therefore, we should not regard the sentinel in the above algorithms as an artifact. Instead, we should have a deep understanding of and master this technique.

Sorting Process for given input instances

The files to be sorted have eight records with the keywords: 49,38, 65,97, 13, 27,49. To distinguish two identical keywords 49, the lower part of the last 49 is underlined to show the difference. For the sorting process, see [Animation Simulation Demonstration]

Algorithm Analysis

1. algorithm time Performance Analysis

For files with N records, n-1 sort is required.
Time Complexity in various states:
┌ ── ─ ┬ ── ─
│ Initial File status │ forward/reverse/unordered (average) │
├ ── ─ ┼ ── ─
│ Key │ 1 │ I + 1 │ (I-2)/2 │
│ Word comparison times │
├ ── ─ ┼ ── ─
│ Total keyword comparison times │ n-1 │ (n + 2) (n-1)/2 │ ≈ N2/4 │
├ ── ─ ┼ ── ─
│ I trip records mobile times │ 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) │
└ ── ─ ┴ ── ─
Note:
The initial file is incremental and ordered by keywords, or "Forward" for short ".
The initial file is in descending order by keyword, or "Reverse Order" for short ".

2. spatial complexity analysis of Algorithms
The auxiliary space required by the algorithm is a monitoring whistle, and the complexity of the auxiliary space is S (n) = O (1 ). Is a local sorting.

3. Stability of direct insertion sorting
Directly inserting sorting is a stable sorting method.

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.