The following describes the direct insertion sorting, binary insertion sorting, table insertion sorting, and shell sorting in sequence.
1. Sort directly inserted
It is a bit similar to playing poker. Every time you grab a card, you can put the small one on the left and the big one on the right. That is to say, the sub-cards in the hand are always sorted from small to large. Each card is compared with the rightmost card in sequence, knowing that one card is smaller or equal than it, after this card.
C language implementation:
Void insertionsort (int * data, int Len) {If (LEN <= 1) return; For (INT I = 1; I <Len; I ++) {int value = data [I]; Int J = I-1;
// Note: If you can use the 0th elements of data as the sentry, and the elements to be sorted start with 1st, you can set data [0] = data [I] each time. directly judge data [J]> data [0], so it is unnecessary to Judge J> = 0 while (j> = 0 & Data [J]> value) {data [J + 1] = data [J]; // move the large record back to j --;} data [J + 1] = value; // insert record }}
Ii. Binary direct insertion sorting
Directly Insert the sorting method each time the I + 1 records are encountered, the order is required with the front I, I-1 ,... record (s) are compared. Since the first I records have been sorted, you can refer to the Binary Search Method to compare them with the second (I + 1)/second records, in this way, the scope is gradually reduced to reduce the number of comparisons.
Iii. Sort table Inserts
For arrays with sequential access, each insertion process is accompanied by a large number of post-migration operations. Therefore, we can consider modifying the record type structure by using a two-way linked list, in this way, the moving operation can be avoided. You only need to modify the pointer values before and after the target position.
4. Shell sorting