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

时间:2023-03-09 05:15:46
2-路插入排序(2-way Insertion Sort)的C语言实现
原创文章,转载请注明来自钢铁侠Mac博客http://www.cnblogs.com/gangtiexia
2-路插入排序(2-way Insertion Sort)的基本思想:
    比fisrt小的元素,插入first前面;
    比final大的元素,插入final后面,
    比fisrt大且比final小的元素插中间
演示实例:
2-路插入排序(2-way Insertion Sort)的C语言实现
C语言实现(编译器Dev-c++5.4.0,源代码后缀.cpp)
 #include <stdio.h>
#define LEN 6 typedef float keyType; typedef struct{
keyType score;
char name[];
}student; typedef struct{
int length=LEN;
student stu[LEN];
}sqList; void two_WayIS(sqList &L){
sqList temp;
int first=,final=;
temp.stu[first]=L.stu[];
for(int i=;i<L.length;i++){
if(L.stu[i].score>temp.stu[final].score){//插final后面
temp.stu[i]=L.stu[i];
final++;
}else if(L.stu[i].score<temp.stu[first].score){ //插first前面
if(first==) first--; //数组以1开始
first=(first-+L.length)%L.length; //first变化为1->5->4>3>2......
temp.stu[first]=L.stu[i];
}else if(L.stu[i].score<temp.stu[final].score){ //插中间
int p=(final-+L.length)%L.length;
if(p==) p--;
while(L.stu[i].score<temp.stu[p].score){
p=(p-+L.length)%L.length;
if(p==) p--;
}
final++;
int k=final;
while(k>(p+)){
temp.stu[k]=temp.stu[k-];
k=(k-+L.length)%L.length;
if(k==) k--;
}
temp.stu[p+]=L.stu[i]; }
}
} int main(){
sqList L; for(int i=;i<L.length;i++){
printf("\n请输入第%d个学生的姓名:",i);
gets(L.stu[i].name);
printf("分数:");
scanf("%f",&(L.stu[i].score));
getchar();
} two_WayIS(L); for(int i=;i<L.length;i++){
printf("\n学生%s 分数%f 第%d名",L.stu[i].name,L.stu[i].score,i);
}
return ;
}
2-路插入排序(2-way Insertion Sort)的C语言实现