2010-11-24 108 views
1

如何在函数中对char firstName进行排序,并且已经从文本文件中读入名称,并且还可以使用外部库 所有学生的名字都以文本文件,该文件被读入学生的阵列记录如何使用C语言对结构中的char名称进行排序

struct student{ 
    char*lastName; /*name of the student*/ 
    char*firstName; 
    int age;  /*age of the student*/ 
    float grade[3]; 
} 
+0

您可以通过选择并按下CTRL + K来格式化代码。使用预览。 – EboMike 2010-11-24 22:10:05

+0

此外,您的问题没有提供足够的信息。你有什么样的阵列/集合?这个结构没有告诉我们任何东西。 – EboMike 2010-11-24 22:10:41

回答

0

最简单的方式,假设你不允许使用外部库,是冒泡。编写一个函数来确定struct student的数组是否已经排序。然后编写一个遍历这个数组的函数,比较相邻的学生对。如果它们出现故障,请交换它们。使用第一个函数的结果作为while循环的条件子句,第二个函数作为主体。

如果您可以使用它,那么从stdlib.hqsort()是迄今为止最好的方法。

+0

插入排序通常是触摸更简单,触摸更快。此外,`qsort()`不是外部库,但包含在C标准库中。 – 2010-11-24 22:30:37

4

qsort函数通常用于C中对数组进行排序。其中一个参数是指向比较函数的指针。编写该函数,以便以任何您想要的方式比较这两个指针。您甚至可以使用不同的比较函数,以便在运行时选择将应用的选项。

int StudentCompare(const void * elem1, const void * elem2) 
{ 
    const struct student * left = (const struct student *) elem1; 
    const struct student * right = (const struct student *) elem2; 
    int result; 
    result = strcmp(left.firstName, right.firstName); 
    if (result == 0) 
     result = strcmp(left.lastName, right.lastName); 
    return result; 
} 
相关问题