题解 | #成绩排序#
成绩排序
http://www.nowcoder.com/practice/8e400fd9905747e4acc2aeed7240978b
//结构体排序,比较简单,要注意熟练使用mcmcpy交换结构体就行
#include "stdio.h"
#include "string.h"#define uint8_t unsigned char
#define int8_t signed char
#define uint16_t unsigned short
#define int16_t signed short
#define uint32_t unsigned int
#define int32_t signed int
typedef struct{
char name[32];
uint16_t score;
}user_t;
void swap_user(user_t* user1,user_t* user2)
{
user_t temp = {0};
memcpy(&temp, user1, sizeof(user_t));
memcpy(user1, user2, sizeof(user_t));
memcpy(user2, &temp, sizeof(user_t));
}
void sort(user_t* user,uint8_t len,uint8_t flag)
{
user_t temp = {0};
if(flag == 1){
for(uint8_t i=0;i<len-1;i++)
for(uint8_t j=0;j<len-i-1;j++)
{
memset(&temp,0, sizeof(user_t));
if(user[j].score > user[j+1].score)
swap_user(&user[j], &user[j+1]);
}
}
else{
for(uint8_t i=0;i<len-1;i++)
for(uint8_t j=0;j<len-i-1;j++)
{
memset(&temp,0, sizeof(user_t));
if(user[j].score < user[j+1].score)
swap_user(&user[j], &user[j+1]);
}
}
for(uint8_t i=0;i<len;i++)
printf("%s %d\n",user[i].name,user[i].score);
}
int main()
{
user_t user[201] = {0};
uint8_t num = 0,flag = 0;
while(scanf("%d%d",&num,&flag)!=EOF)
{
for(uint8_t i=0;i<num;i++)
{
scanf("%s %d",user[i].name,&user[i].score);
}
sort(user,num,flag);
}
}