Preface
The basic idea of insertion sort: each time a record to be sorted is inserted into the previous sorted Sequence Based on its keyword size until all records are inserted.
The basic idea of directly inserting sorting is assumed that the records to be sorted are stored in the array R [1. N. In the initial phase, R [1] is a self-contained ordered zone, and the unordered zone is R [2 .. n]. from I = 2 until I = N, insert R [I] into the current ordered zone R [1 .. in I-1], an Ordered Partition Containing N records is generated. the sorting method records the keywords of the record R [I] from right to left and records R [J] (j = I-1, i-2 ,...., 1) keyword comparison:
- If the keyword of R [J] is greater than the keyword of R [I], move R [J] to a position.
- If the keyword of R [J] is smaller than or equal to the keyword of R [I], the search process ends. J + 1 is the R [I] Insert position.
Records with larger keywords than those of R [I] have been moved backward, so the position of J + 1 has been vacated, you just need to insert R [I] directly to this location to complete a bit of direct insertion sorting C language implementation code
Insertsort. c
# Include <stdio. h> typedef int elementtype; elementtype arr [10] = {,}; elementtype arr1 [11] =, 6, 44, 98}; // do not use the sentry. Each cycle needs to compare void insertsort (elementtype A [], int N) {int I, j; elementtype temp; for (I = 1; I <n; I ++) {temp = A [I]; for (j = I; j> 0; j --) {if (a [J-1]> temp) A [J] = A [J-1]; else break;} A [J] = temp ;}} /* use a [0] As the sentry. The sentry has two functions: 1. temporarily store the elements to be inserted. 2. Prevent the array subscript from crossing the border, combine j> 0 with a [J]> temp to compare a [J]> A [0] only once. In this way, the for loop is compared only once, improving the efficiency, the for loop has two judgment conditions */void withsentrysort (elementtype A [], int N) {int I, j; for (I = 2; I <n; I ++) {A [0] = A [I]; for (j = I-1; A [J]> A [0]; j --) {A [J + 1] = A [J];} A [J + 1] = A [0];} void print (elementtype A [], int N) {int I; for (I = 0; I <n; I ++) {printf ("% d", a [I]) ;}} int main () {print (ARR, 10); printf ("\ n"); insertsort (ARR, 10); print (ARR, 10); printf ("\ n "); withsentrysort (arr1, 11); print (arr1, 11); printf ("\ n"); Return 0 ;}
The running result is as follows: