Insert sorting is a type of simple sorting. It is mainly used to sort a small amount of data, and there is no advantage in a large amount of data. Insertion sorting is like playing poker. When you touch a card, you can see it and insert it to the proper position according to the order of the cards in your hand. It is a sort of data first and then location.Algorithm. Different from the sorting algorithm.
The followingCodeA simple exercise of insertion sorting is implemented.
# Include <stdio. h> # define maxsize 50int * insert_sort (int * s, int N); int main (void) {int N, I; int s [maxsize + 1]; // one more secondary element: printf ("insert sort exercise \ n"); printf ("Enter the number of digits you want to sort:"); scanf ("% d ", & N); getchar (); printf ("Enter the data to be sorted in sequence \ n"); for (I = 1; I <n + 1; I ++) // element 0 serves as the auxiliary element {scanf ("% d", & S [I]);} insert_sort (S, N); printf ("the output of sorted data is: \ n "); for (I = 1; I <n + 1; I ++) {printf (" % d ", s [I]);} printf ("\ n");} int * insert_sort (int * s, int N) {int I, j; for (I = 2; I <n + 1; I ++) // I subscript indicates the selected element to be sorted {s [0] = s [I]; j = I-1; // The part before the J subscript indicates that the while (s [0] <s [J]) {s [J + 1] = s [J] is sorted; // move element after j --;} s [J + 1] = s [0]; // insert element }}
Insert sorting consists of two parts: Comparison and moving. The workload for one comparison is higher, and the workload for moving is smaller.
It has low overhead and only needs one slave unit, that isProgramElement of array subscript 0. In addition, two auxiliary variables are usually used for sorting I and j, which is suitable for Embedded Systems with tight memory resources.
In addition, the time complexity of insertion sorting is proportional to the number of data elements. The time complexity is O (n ^ 2 ). Insert sorting supports static sorting and dynamic sorting, just like playing poker.