如何解决如何按名称,年龄和ID对C中的结构数组排序?
我不知道如何使函数按值对结构数组排序。任何提示都是有帮助的。
我很困惑如何将值传递给函数,然后按年龄,名称对结构列表进行排序。
我想看看如何组织结构数组,因为以后我将不得不使用多个具有名称,年龄,ID的文件。
//- Functions needed
//Swap
//Selection sort
//Bubble sort
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct person
{
int age;
double id;
char name[64];
} person;
int main()
{
person **array = calloc(2,sizeof(person*));
int sizes[2];
for (int i = 0; i < 5; i++) {
array[i] = calloc(sizes[i],sizeof(person));
}
//Num1
strcpy(array[1][0].name,"0yblTP");
array[1][0].id = 7.567;
array[1][0].age = 34;
//Num 2
strcpy(array[1][1].name,"t700nwzB");
array[1][1].id = 8.6576;
array[1][1].age = 85;
//Num3
strcpy(array[1][2].name,"Vx8eR");
array[1][2].id = 179;
array[1][2].age = 59;
//Num4
strcpy(array[1][3].name,"n5FUgA");
array[1][3].id = 1.082797;
array[1][3].age = 45;
//Num5
strcpy(array[1][4].name,"Bzm9dq");
array[1][4].id = 179;
array[1][4].age = 23;
}
解决方法
我认为“发送一组人员”来对函数进行排序,并在函数中对它们进行排序很好地解决了您的问题。
void main {
//Swap (&person,&person) === Swap(&array[1][i],&array[i][j])
//Selection sort(array[1])
//Bubble sort(array[1])
}
像这样。这会将您的人员数组的地址发送到每个排序函数,因此您只需要在内部执行每个函数即可。
void selectionSort(person*) {
for(int i = 0; i < length of person array; i++) {
(algorithm for sorting your person by age,name)
you can use them by person[i].age
}
}
像这样
-
我认为将结构放入数组比您的技巧好
person* A = calloc.. A.name = ".." A.id = ".." A.age = ".." //and then put your struct in the array array[1][i] = A;
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。