, a direct insertion sort algorithm is used to realize the sorting algorithm of sequential table. Resolved as follows.
1 record type structure and order table structure
typedef struct RECORDTYPE
{
int key;
Char data[20];
}recordtype;
#define MAXSIZE 20
typedef struct SQLIST
{
RecordType r[maxsize + 1];
int length;
}sqlist;
2. Building algorithm Classes
Class Calogrithm
{
Public
void cout (void); Display output
void Setmemkey (int i, int k); Set the value of a sort key field
void SetLength (int l); Set the length of a sort
void Insertsort (); Sorting algorithm implementation
Private
SqList T;
};
Implementation functions
void Calogrithm::insertsort ()
{
SqList & L = t;
int i=0, j=0;
for (i=2; i<=l.length; i++)
{
if (L.r[i].key < L.r[i-1].key)
{
L.r[0] = L.r[i];
j = i-1;
while (L.r[0].key < L.r[j].key)
{
L.R[J+1] = L.r[j];
j--;
}
L.R[J+1] = l.r[0];
}
}
};
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, T.r[i].key);
printf ("----------++++++++++++---------------------/n");
}
Sorting Core Algorithm Description
One, treat the first record as an ordered subsequence
Second, sequentially, from the second record, insert the ordered subsequence 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 output.
----------++++++++++++---------------------
Before sort r[1].key=6
Before sort r[2].key=20
Before sort r[3].key=15
Before sort r[4].key=7
Before sort r[5].key=3
----------++++++++++++---------------------
----------++++++++++++---------------------
Before sort r[1].key=3
Before sort r[2].key=6
Before sort r[3].key=7
Before sort r[4].key=15
Before sort r[5].key=20
----------++++++++++++---------------------
Press any key to continue
The complexity of the time. Best case = O (n^2)