代码:
#include<stdio.h>
#include<stdlib.h>
#define m 3
struct student{
long cardnum;;
char name[20];
char academy[20];
long class_num;
};
void input(struct student stu[m])
{
int j,i=1;
for(j=0;j<m;j++)
{
printf("请输入第%d个同学的卡号:",i);
scanf("%ld",&stu[j].cardnum);
printf("请输入第%d个同学的姓名:",i);
scanf("%s",stu[j].name);
printf("请输入第%d个同学的院系:",i);
scanf("%s",stu[j].academy);
printf("请输入第%d个同学的班级:",i);
scanf("%ld",&stu[j].class_num);
i++;
printf("--------------------------\n");
}
}
void quicksort(struct student stu[m],int left,int right)
{
int i,j;
struct student p;
if(left<right)
{
i=left+1;
j=right;
while(i<j)
{
if(stu[i].cardnum > stu[left].cardnum)
{
p=stu[i];
stu[i]=stu[left];
stu[left]=p;
j--;
}
else
{
i++;
}
}
if(stu[i].cardnum >= stu[left].cardnum)
{
i--;
}
p=stu[left];
stu[left]=stu[i];
stu[i]=p;
quicksort(stu,left,i);
quicksort(stu,j,right);
}
}
void sort(struct student stu[m])
{
int i,j;
struct student p;
for(i=0;i<m;i++)
{
for(j=i+1;j<m;j++)
{
if(strcmp(stu[i].name,stu[j].name)>0)
{
p=stu[i];
stu[i]=stu[j];
stu[j]=p;
}
}
}
}
int twice_find(struct student stu[m],int key)
{
int low,high=m-1,mid;
while(low<=high)
{
mid=(low+high)/2;
if(stu[mid].cardnum == key) return mid;
if(stu[mid].cardnum>key)
high=mid-1;
else
low=mid+1;
}
return -1;
}
void display(struct student stu[m])
{
int i;
printf("学生信息如下:\n");
printf("--------------------------\n");
for(i=0;i<m;i++)
{
printf("卡号:%ld\n姓名:%s\n院系:%s\n班级:%ld\n",stu[i].cardnum,stu[i].name,stu[i].academy,stu[i].class_num);
printf("--------------------------\n");
}
}
int main()
{
struct student stu[m];
int i,key,j;
printf("请输入借书同学的信息:\n");
printf("--------------------------\n");
input(stu);
printf("请选择你想要的功能:\n");
printf("1.按照卡号进行排序。\n");
printf("2.按照姓名进行排序。\n");
printf("3.二分查找同学的信息。\n");
printf("4.退出系统。\n");
scanf("%d",&i);
switch(i)
{
case 1:
quicksort(stu,0,m-1);
printf("排序结果为:\n");
display(stu);
break;
case 2:
sort(stu);
printf("排序结果为:\n");
display(stu);
break;
case 3:
printf("请输入要查找的同学的卡号:");
scanf("%d",&key);
j=twice_find(stu,key);
printf("卡号:%ld\n姓名:%s\n院系:%s\n班级:%ld\n",stu[j].cardnum,stu[j].name,stu[j].academy,stu[j].class_num);
break;
case 4:
break;
}
return 0;
}