插入排序法的示例
1
2
#include <stdio.h>
3![]()
4
#define MAX 10
5![]()
6
typedef int KeyType;
7![]()
8
typedef struct node
9
{
10
KeyType Key;
11
}RecType;
12
//初始化数组
13
void Initialize(RecType R[])
14
{
15
int i;
16
KeyType Temp[MAX]={85,15,67,1,5,0,69,56,44,3};//排序序列
17![]()
18
for(i=1;i<=MAX;i++)
19
{
20
R[i].Key=Temp[i-1];
21
}
22
}
23
//打印数组
24
void Print(RecType R[])
25
{
26
int i;
27
for(i=1;i<=MAX;i++) printf("%d ",R[i].Key);
28
printf("\n");
29
}
30
//插入排序
31
void InsertSort(RecType R[])
32
{
33
int i,j;
34![]()
35
for(i=2;i<=MAX;i++)
36
{
37
if(R[i].Key<R[i-1].Key)
38
{
39
R[0]=R[i];
40
for(j=i-1;R[0].Key<R[j].Key;j--)//查找位置
41
R[j+1]=R[j];//元素后移
42
R[j+1]=R[0];
43
}
44
printf("第%d次操作结果:",i-1);
45
Print(R);
46
}
47
}
48
//main函数
49
int main()
50
{
51
RecType R[MAX+1];
52![]()
53
Initialize(R);
54
printf("排序序列为:");
55
Print(R);
56
InsertSort(R);
57
printf("最终排序结果为:");
58
Print(R);
59![]()
60
return 0;
61
}
62![]()
63![]()
2
#include <stdio.h>3

4
#define MAX 105

6
typedef int KeyType;7

8
typedef struct node9
{10
KeyType Key;11
}RecType;12
//初始化数组13
void Initialize(RecType R[])14
{15
int i;16
KeyType Temp[MAX]={85,15,67,1,5,0,69,56,44,3};//排序序列17

18
for(i=1;i<=MAX;i++)19
{20
R[i].Key=Temp[i-1];21
}22
}23
//打印数组24
void Print(RecType R[])25
{26
int i;27
for(i=1;i<=MAX;i++) printf("%d ",R[i].Key);28
printf("\n");29
}30
//插入排序31
void InsertSort(RecType R[])32
{33
int i,j;34

35
for(i=2;i<=MAX;i++)36
{37
if(R[i].Key<R[i-1].Key)38
{39
R[0]=R[i];40
for(j=i-1;R[0].Key<R[j].Key;j--)//查找位置41
R[j+1]=R[j];//元素后移42
R[j+1]=R[0];43
}44
printf("第%d次操作结果:",i-1);45
Print(R);46
}47
}48
//main函数49
int main()50
{51
RecType R[MAX+1];52

53
Initialize(R);54
printf("排序序列为:");55
Print(R);56
InsertSort(R);57
printf("最终排序结果为:");58
Print(R);59

60
return 0;61
}62

63



KeyType Temp[MAX]
浙公网安备 33010602011771号