对于待排序序列A[1, n],遍历整个序列,每次保证前1至n个数排列正确;
View Code
1 /*
2 * insertion sort
3 * 2011-9-29
4 */
5
6 #include <stdio.h>
7 #include <stdlib.h>
8
9 #define MAX_UNIT (7)
10
11 unsigned int g_unit[MAX_UNIT] = {8,2,4,9,3,6,1};
12
13 static void sort_showlist();
14
15 static void sort_insertion(unsigned int *pUnit, unsigned int num);
16
17
18 void main(void)
19 {
20 sort_insertion(g_unit, MAX_UNIT);
21
22 sort_showlist();
23
24 system("pause");
25
26 return;
27 }
28
29 static void sort_insertion(unsigned int *pUnit, unsigned int num)
30 {
31 unsigned int j = 0;
32 unsigned int i = 0;
33 unsigned int key =0;
34
35 for (j = 1; j < num; j++)
36 {
37 key = *(pUnit + j);
38
39 for (i = 0; i < j; i++)
40 {
41 if (key < *(pUnit + i))
42 {
43
44 *(pUnit + j) = *(pUnit + i);
45 *(pUnit + i) = key;
46 key = *(pUnit + j);
47
48 sort_showlist();
49 }
50
51
52 }
53 }
54
55 return;
56 }
57
58
59 static void sort_showlist()
60 {
61 unsigned int i = 0;
62
63 for (i = 0; i < MAX_UNIT; i++)
64 {
65 printf("%d ", g_unit[i]);
66 }
67
68 printf("\r\n");
69
70 return;
71 }