您的位置:首页 > 编程语言 > C语言/C++

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

2016-01-03 21:16 543 查看
原创文章,转载请注明来自钢铁侠Mac博客http://www.cnblogs.com/gangtiexia

2-路插入排序(2-way Insertion Sort)的基本思想:
比fisrt小的元素,插入first前面;
比final大的元素,插入final后面,
比fisrt大且比final小的元素插中间

演示实例:



C语言实现(编译器Dev-c++5.4.0,源代码后缀.cpp)

#include <stdio.h>
#define LEN 6

typedef float keyType;

typedef struct{
keyType score;
char name[20];
}student;

typedef struct{
int length=LEN;
student stu[LEN];
}sqList;

void two_WayIS(sqList &L){
sqList temp;
int first=1,final=1;
temp.stu[first]=L.stu[1];
for(int i=2;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==1) first--; //数组以1开始
first=(first-1+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-1+L.length)%L.length;
if(p==1) p--;
while(L.stu[i].score<temp.stu[p].score){
p=(p-1+L.length)%L.length;
if(p==1) p--;
}
final++;
int k=final;
while(k>(p+1)){
temp.stu[k]=temp.stu[k-1];
k=(k-1+L.length)%L.length;
if(k==1) k--;
}
temp.stu[p+1]=L.stu[i];

}
}
}

int main(){
sqList L;

for(int i=1;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=1;i<L.length;i++){
printf("\n学生%s 分数%f 第%d名",L.stu[i].name,L.stu[i].score,i);
}
return 1;
}


内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: