-1

Ok so the user enter a name and an age. The output needs printed in ascending order. I've done bubble sort but I do not know how to keep track of the ages with the names. Is one sort method better or easy than another one?

IdislikeCalot
  • 41
  • 1
  • 9

1 Answers1

3

Instead of using a bunch of arrays, you can just put everything you need into a struct, make an array of structs. For example:

struct user {
    char name[100];
    int age;
};

struct user user_array[100];

Or, if you don't want to change the whole code, just make a swap function somwhere, and in your sorting algorithm, instead of swapping elements directly, just call a swap function. For example, assume that you have

char name[100][100];
int age[100];

The swap function will look like

void swap_users(int a, int b, char ** name, int * age)
{
    int age_tmp;
    char *name_tmp;
    age_tmp  = age [a]; age [a] = age [b]; age [b] = age_tmp;
    name_tmp = name[a]; name[a] = name[b]; name[b] = name_tmp;
}

And your sorting algorithm will look like:

void some_sorting_algorithm()
{
    // do something ...
    // do something ...
    // maybe some loop? ...
        swap_users(x, y, name, age);
    // continue the loop or doing something
}

PS: hope I understood your question correctly.

Chan Kha Vu
  • 9,834
  • 6
  • 32
  • 64
  • I like that swap function but I'm not sure i understand it. Could you explain the asterisks? Pointers? – IdislikeCalot Apr 15 '15 at 23:01
  • Asterisk in declaration means that it's a pointer to a type. Technically, an array is a pointer. For example, `int *age` -> age is a pointer to integer, `int age[100]` -> age is also a pointer to integer`char ** name` -> so name is a pointer to a pointer to char (in declaration `char name[100][100]` -> name is also a pointer to a pointer to char). – Chan Kha Vu Apr 15 '15 at 23:14
  • Suggestion: rather the use 100 and 100 for name size and user_array size, use 2 different constants: Easier for new folks to follow your nice example/ – chux - Reinstate Monica Apr 15 '15 at 23:43
  • Ok thanks guys I'm with option two only because it was written already. I really will read into the strut idea. – IdislikeCalot Apr 16 '15 at 00:19