c - 如何在C中对一组结构进行排序

标签 c sorting struct

我创建了 4 个变量结构并为 age 分配了值。

 struct database {
 int id_number;
 int age;
 float salary;
 };

 main()
 {
 struct database employee[4];
 struct database current; // Used later in my attempted sorting

 employee[1].age = 12;

 employee[2].age = 112;

 employee[3].age = 2;

 employee[4].age = 22;

我尝试了各种方法来尝试对这些进行排序,但都失败了, 例如:

 for(i = 0; i < 4; i++)
 {
     current = employee[i];//"current" was previously assigned to the same type of struct
     j = i;

     while(employee[j-1].age > current.age)
     {
        employee[j] = employee[j-1];
        j = j-1;
     }
     employee[j] = current;
 }

最佳答案

许多错误,正如其他人在评论中指出的那样。

(数组访问越界、排序算法不正确等)

<小时/>

要对struct数组进行排序,最简单的方法是使用 qsort 您需要定义自定义比较器,如下所示:

typedef struct database db;

int sort_by_age(void *a, void *b)
{
  db *_a = (db *)a;
  db *_b = (db *)b;

  if( _a->age > _b->age  ) return -1;
  if( _a->age == _b->age ) return 0;

  return 1;
}

然后像这样使用它,

int no_of_employee = 4;

qsort( employee, no_of_employee, sizeof(db), sort_by_age );

关于c - 如何在C中对一组结构进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22967670/

相关文章:

c - MexFile 导致 "Assertion detected"错误 - mexfiles 中的 memcpy 有问题吗?

sorting - 根据Ansible中的特定值对dict进行排序

c - 定义一个在 C 头文件中传递结构的函数

c++ - 在模板元编程中使用 "struct xxx<>::val"导致错误

c++ - 阻止编译器在具有遗留 C 代码的 C++ 代码中生成错误

c - 使用 ANSI C 将二进制图像数据从数据库中提取到 .jpg 文件中

algorithm - 这种有名字吗?

swift - 如何使用struct在swift中显示UIImage

c - 寻找 `COMPILE_WPRINTF` 的定义

c - Kylix 中的 TEvent.WaitFor