Question, use the direct insertion of the sort algorithm to achieve the ordering algorithm for the sequence table. Solve as follows.
1 record type structure and sequential table structure
TypedEf struct recordtype {int key; char data [20];} RecordType;
#define maxSize 20
Typedef struct sqlist {recordtype r [maxsize 1]; intlene;} sqlist;
2. Establish an algorithm class
Class CalogritHM {public: Void Cout (Void); // Display Output Void SetMemKey (INT I, INT K); Set the value of the sorting key field "Void setLength (int L); set the length of the sorted void insert (); // Sort algorithm realizes private: SQLIST T;};
// Implement function
Void Calogrithm :: InsertSort () {SQLIST & L = T; INT i = 0, J = 0; for (i = 2; i <= L.LENGTH; I ) {IF (LR [i] .Key Void Calogrithm :: SETLENGTH (INT L) {this-> t.length = L;} Void Calogrithm :: setMemKey (int i, int k) {this-> T.R [i] .key = k;} Void Calogrithm :: cout () {INT i = 0; Printf ("---------- ------------ -------- / N "); for (i = 1; i <= t.length; i ) printf (" Before Sort R [% D] .key =% d / n ", i, Tr [I] .key); Printf ("---------- ----------------- ---- / n "); } Sorting core algorithm description First, the first record is regarded as a sequence of sequences Second, in turn, from the second record, insert the order-by-order sequence by comparison. // Client test code INT Main (int Argc, char * argv []) {INT i = 0; CalogritHM demo; demo.setLength (5); Demo.setMemKey (1, 6); Demo.setMemKey (2, 20); demo.setMemKey (3, 15); demo.setMemKey (4, 7); demo.setMemKey (5, 3); demo.cout () Demo.insertsort (); demo.cout (); return 0;} // The result is output. -------- -------------------- Before Sort R [1]. Key = 6Before Sort R [2] .key = 20before Sort R [3] .key = 15before sort r [4] .key = 7before sort r [5] .key = 3 ---------- ------------------------------ -------------------- Before sort r [1] .key = 3before sort r [2] .Key = 6Before Sort R [3]. Key = 7Before Sort R [4] .key = 15before sort r [5] .key = 20 ---------- ------- -------------- Press Any Key to Continue Time Complex. Best case = O (n ^ 2)