0

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.

//- 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;

}
Wreo
  • 1
  • 1

1 Answers1

0

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.

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;
    
seenblee
  • 52
  • 4