简体   繁体   English

如何按名称、年龄和 ID 对 C 中的结构数组进行排序?

[英]How do I sort an array of structs in C by name, age and id?

I don't know how to make a function to sort an array of structs by the values.我不知道如何制作一个函数来按值对结构数组进行排序。 Any tips are helpful.任何提示都是有帮助的。

I am confused how to pass the values into a function and then sort the list of structs by the age, then name.我很困惑如何将值传递给函数,然后按年龄和名称对结构列表进行排序。

I want to see how to organize the array of structs as I will later have to use multiple files with names, ages, ids.我想看看如何组织结构数组,因为我以后将不得不使用具有名称、年龄、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;

}

i think 'send an array of person' to sort function and sorting them in the function is good to solve your problem.我认为“发送一组人”对函数进行排序并在函数中对它们进行排序可以很好地解决您的问题。

void main {
  //Swap (&person, &person) === Swap(&array[1][i], &array[i][j])
  //Selection sort(array[1])
  //Bubble sort(array[1])
}

like this.像这样。 this will send address of your person array to each sorting function, so you just need to execute each function inside.这会将你的 person 数组的地址发送到每个排序函数,所以你只需要在里面执行每个函数。

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
  }
}

like this.像这样。

  • i think it is better than your skill to put struct to an array我认为将结构放入数组比你的技能更好

     person* A = calloc.. A.name = ".." A.id = ".." A.age = ".." //and then put your struct in the array array[1][i] = A;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM