使用qsort对结构进行排序(按“姓氏”字段排序)

时间:2014-02-09 20:35:57

标签: c sorting structure qsort

我有这一部分,首先(我将用它来创建员工结构):

    typedef struct 
    { 
       char first_name[20], last_name[20]; 
       int birthdate, temporary; 
       //date of birth YEAR/MONTH/DAY
       //temporary employees: 1, else 0

    }factory;

我将使用以下函数读取数据:

    void reading(factory *employee,int *nr) 
    { 
      ++(*nr); 
      printf("First name:\n");
      fflush(stdin); 
      gets((employee+*nr)->first_name);

      printf("Last name:\n");
      fflush(stdin); 
      gets((employee+*nr)->last_name);

      printf("Birthdate:\n");
      fflush(stdin);
      scanf ("%d" , &((employee + *nr)->birthdate));

      printf("Temporary employee? 1 for YES, 0 for NO");
      fflush(stdin);
      scanf("%d", &((employee + *nr)->temporary));

    }

比较功能(我认为没有正确编写,关于如何修改它的任何建议都会很棒 - 它应该是“工厂员工* ia”而不是结构吗?):

int struct_cmp_by_name(const void *a, const void *b)
{
struct employee *ia = (struct employee *)a;
struct employee *ib = (struct employee *)b;
return strcmp(ia->last_name, ib->last_name);

}

我还有一个简单的显示功能,其原型我将在下面复制:

void display(factory *employee, int nr) 

为了空间,省略了代码的其他部分。在这种情况下,我如何实现qsort函数?我有比较功能,但我不知道基本数组应该是什么或如何找到其他两个大小参数。期待感谢您提供的任何帮助。

1 个答案:

答案 0 :(得分:0)

应该是

工厂* ia =(工厂*)a;

或者你可以跳过作业并只是施放

...((工厂*)a) - > last_name ...

我假设您的代码中某处为工厂数组分配或声明空间?

对于快速排序,您可以交换结构,也可以创建指向结构和交换指针的指针数组。