6.完善P35例2-2 ,增加成绩到学生信息中,并按照成绩从高到低排序后输出学生信息。
头文件:SeqList.h
#include<stdio.h>
#define MaxSize 100
typedef struct Student
{
long number;
char name[10];
char sex[3];
int age;
double score;
}StudentType;
typedef StudentType DataType;
typedef struct
{
DataType list[MaxSize];
int size;
}SeqList;
void ListInitiate(SeqList* L)
{
L->size = 0;
}
int ListLength(SeqList L)
{
return L.size;
}
int ListInsert(SeqList* L, int i, DataType x)
{
int j;
if (L->size >= MaxSize)
{
printf("数组已满无法插入!\n");
return 0;
}
else if (i<0 || i>L->size)
{
printf("参数i不合法!\n");
return 0;
}
else
{
for (j = L->size; j > i; j--)
L->list[j] = L->list[j - 1];
L->list[i] = x;
L->size++;
return 1;
}
}
int ListDelete(SeqList* L, int i, DataType* x)
{
int j;
if (L->size <= 0)
{
printf("顺序表已空无数据可删!\n");
return 0;
}
else if (i<0 || i>L->size - 1)
{
printf("参数i不合法");
return 0;
}
else
{
*x = L->list[i];
for (j = i + 1; j <= L->size - 1; j++)
L->list[j - 1] = L->list[j];
L->size--;
return 1;
}
}
int ListGet(SeqList L, int i, DataType* x)
{
if (i<0 || i>L.size - 1)
{
printf("参数i不合法!\n");
return 0;
}
else
{
*x = L.list[i];
return 1;
}
}
源文件:Sort.c
#include"SeqList.h"
void BubbleSort(DataType a[], int n)
{
int i, j, flag = 1;
DataType temp;
for (i = 1; i < n && flag == 1; i++)
{
flag = 0;
for (j = 0; j < n - i; j++)
{
if (a[j].score > a[j + 1].score)
{
flag = 1;
temp = a[j];
a[j] = a[j + 1];
a[j + 1] = temp;
}
}
}
}
int main()
{
SeqList myList;
int i;
StudentType x[3] = { {2000001,"张三","男",20,92.8},
{2000002,"李四","男",21,99.6},
{2000003,"王五","女",22,79} };
StudentType s;
ListInitiate(&myList);
ListInsert(&myList, 0, x[0]);
ListInsert(&myList, 1, x[1]);
ListInsert(&myList, 2, x[2]);
for (i = 0; i < ListLength(myList); i++)
{
ListGet(myList, i, &s);
printf("%ld %s %s %d %.2f\n", s.number, s.name, s.sex, s.age, s.score);
}
BubbleSort(x, 3);
printf("\n");
for (i = 0; i < 3; i++)
{
printf("%ld %s %s %d %.2f\n", x[i].number, x[i].name, x[i].sex, x[i].age, x[i].score);
}
return 0;
}