首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > C++ >

怎么给结构体排序

2012-03-04 
如何给结构体排序?#include stdio.h #include bios.h #include stdlib.h staticstructs{charname[10

如何给结构体排序?
#include "stdio.h "
#include "bios.h "
#include "stdlib.h "
static   struct   s
{
char   name[10];
int   math;
int   chinese;
int   english;
int   chemistry;
int   physics;
int   biology;
}list[3];
main()
{
  int   point[3],i,j;
  struct   s   t;
int   key;
clrscr();
for(i=0;i <3;i++)
{
printf( "input   the   ESC   to   quit,or   enter   any   other   key\n ");
fflush(stdin);
key=bioskey(0)&0xff;
if((key&27)==27)
break;
else
{
printf( "please   input   the   No.%d   student   information\n ",i+1);
scanf( "%s%d%d%d%d%d%d ",list[i].name,&list[i].math,&list[i].chinese,&list[i].english,   &list[i].chemistry,   &list[i].physics,&list[i].biology);
}
}
  for(i=0;i <3;i++)
  point[i]=list[i].chinese+list[i].english+list[i].chemistry+list[i].physics+list[i].biology;
  for(j=1;j <=3;j++)
    for(i=0;i <=3-j;i++)
          if(point[i] <point[i+1])
          {t=list[i];list[i]=list[i+1];list[i+1]=t;}
  for(i=0;i <3;i++)
  printf( "%s\n ",list[i].name);
}

我的想法是每个list与对应序号的point相对应,按照piont从大到小排序,程序通过编译但是运行以后没有排序效果,只是把原结构体的内容输出来。要怎么解决呢?
该死的课程设计......

[解决办法]
最笨的那个算法叫冒泡啊。简单实用啊。我就经常用。哈哈
[解决办法]
//这个应该没有问题, 上面的忘记交换point了:)
#include "stdio.h "
//#include "bios.h "
#include "stdlib.h "

static struct s
{
char name[10];
int math;
int chinese;
int english;
int chemistry;
int physics;
int biology;
}list[3];

int main()
{
int point[3],i,j;
struct s t;
int key;
//clrscr();
for(i=0;i <3;i++)
{
printf( "input the ESC to quit,or enter any other key\n ");
fflush(stdin);
//key=bioskey(0)&0xff;
printf( "please input the No.%d student information\n ",i+1);
scanf( "%s%d%d%d%d%d%d ",list[i].name,&list[i].math,&list[i].chinese,&list[i].english, &list[i].chemistry, &list[i].physics,&list[i].biology);

}
for(i=0;i <3;i++) point[i]=list[i].chinese+list[i].english+list[i].chemistry+list[i].physics+list[i].biology;

int p;
for(j=0;j <3;j++) {
for(i=0;i <3;i++) {
if(point[i] <point[j]) {
t=list[i];
list[i]=list[j];
list[j]=t;

p = point[i];
point[i] = point[j];
point[j] = p;

}
}
}

for(i=0;i <3;i++) printf( "%s\n ",list[i].name);

}


[解决办法]
结构体中的数据最好和排序的逻辑算法分开.具体选用什么排序算法是根据需求特点来定的.大多数情况下,排序的比较和移动数据时间复杂度都在一个数量级.对于元素个数少于100的情况,快速排序没什么优势.很多时候要求排序稳定(关键值相等的元素不会因为排序而改变前后顺序),快速排序和希尔排序是没法满足要求的.选择排序和冒泡有时是不错的选择.

热点排行