Insert sort (insert sort directly), insert sort directly
1. Insert sorting directly
1) time complexity:T (n) = O (n ^ 2 );
2) space complexity:S (n) = O (1 );
3)Brief Introduction: Direct Insertion Sorting is the most basic insert Sorting method, and direct Insertion Sorting (Straight Insertion Sorting) the basic idea 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, and an unordered table contains n-1 elements, in the sorting process, the first element is extracted from the unordered table each time, and inserted into the appropriate position in the ordered table to make it 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 and 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].
4) Insert sorting directly:
Eg: the sequence to be sorted is {48, 62, 35, 77, 55,14, 35, 98 };
A) First, store the number to be sorted into array a [], and a [0] is not assigned a value (A [0] is a monitoring post, first, it temporarily saves the records to be inserted, and second, it prevents cross-border operations. First, it regards the first number (that is, a [1]) as a single-element subset that has been sorted );
{48}, 98
B) assign a [2] to a [0], and then compare a [2] with a [1, for each comparison, if a [2] is less than a [1] value exchange, otherwise the comparison ends. After the exchange, a [1] is compared with a [0 (We can see that no matter whether a [1] The original a [2], a [0] is equal to the original a [2], no exchange will be made with a [0] in any case, this is the role of a [0] in monitoring and recording)In this example, a [2] = 62> (a [1] = 48), so no exchange is performed;
;
Likewise:
C) {35, 48, 62}, 98;
D) {35, 48,}, 98;
E) {35,48, 55,62, 77}, 98;
F;
G) {14,35, 35,48, 55,62, 77}, 98;
H };
4) source code:
Typedef int KeyType;
Typedef struct {
Keytype key;
OtherType other_data;
} RecordType;
Void InsSort (RecordType r [], int length)
{
For (I = 2; I <= length;
{
R [0] = r [I]; j = I-1;
While (r [0]. key <r [I]. key)
{
R [j + 1] = r [j]; j = J-1;
}
R [j + 1] = r [0];
}
}