我创建了 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/