The sort of inserted tables uses static linked lists to complete sorting in two steps.
1. Insert a new element to an ordered cyclic linked list and modify the direction of the next pointer of each node so that the elements are ordered. In this process, we do not move or exchange elements, but modify the pointer pointing.
2. Adjust the position of the element following the pointer to make it physically ordered in the linked list.
Ideas:
Construct a new struct type to encapsulate the value and pointer fields. Add a node. When a head node is created to create conditions for cyclic termination, the value stored in the Value Field of the header node should not be smaller than the maximum value in the original sequence. Initialize static linked list: the first node and the first node constitute a circular linked list. Since there is only one element in the linked list, it is of course ordered. Insert the subsequent nodes to the circular linked list in sequence, and adjust the pointer direction of each node to make it orderly along the pointer direction.
Key code:
Const int MAX = 1000; // The maximum value here. Set the node type of the typedef struct rec // Record static linked list {int data; int next; // The Link field of the static linked list can be written in this way. You should have seen it many times} Rec; void InsertSort (int a [], int n) // Insert the table {Rec * rec = new Rec [n + 1]; for (int I = 0; I <n; I ++) // assign data to the linked list {rec [I + 1]. data = a [I]; rec [I + 1]. next = 0;} rec [0]. data = MAX; rec [0]. next = 1; // The first node and the first node constitute the circular linked list int p, q; for (int I = 2; I <n + 1; I ++) {q = 0; p = rec [q]. next; // p points to the node to be compared , Q refers to a while (rec [I]. data> = rec [p]. data) //> = ensures the stability of sorting {q = p; p = rec [q]. next;} rec [I]. next = p; rec [q]. next = I;} p = rec [0]. next; int I = 0; while (p! = 0) // follow the pointer of the static linked list to write data back to the original array {a [I ++] = rec [p]. data; p = rec [p]. next;} delete [] rec; // release space}
Conclusion: insert sorting is because a new data is inserted into the originally ordered sequence each time and compared from the sequence header. Check whether the problem exists. P.s can also change the static linked list to physical order, which is relatively simple. Let's take a look at it and add it later.