数据结构-折半插入排序

见如下截图:

程序代码如下:

 1 #include <stdio.h>
 2 #include <stdlib.h>
 3 #include <time.h>
 4 #define MAXSIZE 20
 5 typedef int KeyType;
 6 typedef char InfoType;
 7 
 8 //结构体定义
 9 typedef struct {
10     KeyType key;
11     InfoType otherinfo;
12 }RedType;
13 typedef struct {
14     RedType r[MAXSIZE+1];
15     int length;
16 }SqList;
17 
18 //各个函数定义
19 void print(SqList *L);
20 void init(SqList *L);
21 void BInsertSort(SqList *L);
22 
23 //初始化,随机产生待排序的数组
24 void init(SqList *L) {
25     int n,i;
26     printf("请输入待排序的元素个数:");
27     scanf("%d",&n);
28     srand(((int)time(0)));//设置随机种子
29     for(i=1; i<=n; i++) {
30         L->r[i].key = rand()%10+1;
31     }
32     L->length = n;
33     printf("随机产生的待排数组为:");
34     print(L);
35     printf("\n");
36 }
37 
38 //输出数组元素
39 void print(SqList *L) {
40     int i;
41     for(i=1; i<=L->length; i++) {
42         printf("%d ",L->r[i].key);
43     }
44     printf("\n");
45 }
46 
47 //进行折半插入排序
48 void BInsertSort(SqList *L) {
49     int low,mid,high,i,j;
50     for(i=2; i<=L->length; i++) {
51         L->r[0] = L->r[i];
52         low = 1;
53         high = i-1;
54         while(low<=high) {
55             mid = (low+high)/2;
56             if(L->r[0].key < L->r[mid].key) {
57                 high = mid-1;
58             } else {
59                 low = mid+1;
60             }
61         }
62         for(j=i-1; j>=high+1; --j) {
63             L->r[j+1] = L->r[j];
64         }
65         L->r[high+1] = L->r[0];
66         printf("第%d次排序的结果为:",i-1);
67         print(L);
68     }
69     printf("\n");
70 
71 }
72 
73 //主函数
74 int main()
75 {
76     SqList sq;
77     init(&sq);
78     BInsertSort(&sq);
79     printf("排序之后的数组为:");
80     print(&sq);
81     return 0;
82 }

 

posted @ 2015-03-24 20:24  橙子123  阅读(327)  评论(0编辑  收藏  举报