1

I am developing a c program. I am using this struct:

main.h:

#define LONG_CADENA 22
#define NUM_CADENAS 5
#define formato "%22s%22s%22s%22s%22s\n"
#define indi_format "%22s"

typedef struct Agenda
{
    char*          nom[NUM_CADENAS];
    struct Agenda* ant;
    struct Agenda* sig;
} ag;

I have this function to show the object Agenda:

#include <stdio.h>
#include "main.h"

ag* mostrarAgenda(ag* act)
{
    unsigned i = 0;
    void*    ini;

    ini = act;
    while (act++->sig)  //ma1: Reescribir esta línea utilizando el bucle for
    {
        for (; i<NUM_CADENAS; i++)
        {
            printf(indi_format, act->nom[i]);
        }
    }

    printf("\n");
    getchar();

    return ini;
}

I need change this function to sort the structs by one of the elements, for example by ag->nom[0]. But im starting with C, and I dont know how I could do it

Somebody could help me?

meaning-matters
  • 21,929
  • 10
  • 82
  • 142
alberph
  • 61
  • 3
  • 13

1 Answers1

0

You can bubble sort it:

int c;
do {
    c=0;
    while(iterator->sig){
       if ( compare(iterator,iterator->sig) > 0 ) {
          swap(iterator,iterator->sig);
          c++;
       }
       iterator=iterator->sig;
    }
 } while (c);

You just have to implement the compare function, and the swap function.

Here the iterator is a pointer to the first element of the list initially. It is your duty to find it.

Also I would suggest in the print function to find the head of the list to start printing unless you are sure that the function is always passed the head of the list as parameter.

George
  • 1,027
  • 3
  • 12
  • 20