2-路插入排序(2-way Insertion Sort)的C语言实现

原创文章,转载请注明来自钢铁侠Mac博客http://www.cnblogs.com/gangtiexia
 
2-路插入排序(2-way Insertion Sort)的基本思想:
    比fisrt小的元素,插入first前面;
    比final大的元素,插入final后面,
    比fisrt大且比final小的元素插中间
 
演示实例:
 
 
C语言实现(编译器Dev-c++5.4.0,源代码后缀.cpp)
 1 #include <stdio.h>
 2 #define LEN 6
 3 
 4 typedef float keyType;
 5 
 6 typedef struct{
 7     keyType score;
 8     char name[20];
 9 }student;
10 
11 typedef struct{
12     int length=LEN;
13     student stu[LEN];
14 }sqList;
15 
16 void two_WayIS(sqList &L){
17     sqList temp;
18     int first=1,final=1;
19     temp.stu[first]=L.stu[1];
20     for(int i=2;i<L.length;i++){
21         if(L.stu[i].score>temp.stu[final].score){//插final后面 
22             temp.stu[i]=L.stu[i];
23             final++;
24         }else if(L.stu[i].score<temp.stu[first].score){ //插first前面 
25             if(first==1) first--; //数组以1开始 
26             first=(first-1+L.length)%L.length; //first变化为1->5->4>3>2......
27             temp.stu[first]=L.stu[i];
28         }else if(L.stu[i].score<temp.stu[final].score){ //插中间 
29             int p=(final-1+L.length)%L.length;
30             if(p==1) p--;
31             while(L.stu[i].score<temp.stu[p].score){
32                 p=(p-1+L.length)%L.length;
33                 if(p==1) p--;
34             }
35             final++;
36             int k=final;
37             while(k>(p+1)){
38                 temp.stu[k]=temp.stu[k-1];
39                 k=(k-1+L.length)%L.length;
40                 if(k==1) k--;
41             } 
42             temp.stu[p+1]=L.stu[i];
43             
44         } 
45     }
46 }
47 
48 int main(){
49     sqList L;
50 
51     for(int i=1;i<L.length;i++){
52         printf("
请输入第%d个学生的姓名:",i);
53         gets(L.stu[i].name);
54         printf("分数:");
55         scanf("%f",&(L.stu[i].score));
56         getchar();
57     }    
58     
59     two_WayIS(L);
60     
61     for(int i=1;i<L.length;i++){
62         printf("
学生%s 分数%f 第%d名",L.stu[i].name,L.stu[i].score,i);
63     }
64     return 1;
65 }
 
原文地址:https://www.cnblogs.com/gangtiexia/p/5097191.html