yeetboi
yeetboi

Reputation: 29

How to sort something with type of struct

I have a structure ElementType

typedef struct
{
    int AtomicNumber;
    char Name[31];
    char Symbol[4];
} ElementType;

I am trying to implement a sorting algorithm that will sort the elements alphabetically. I compare the strings but nothing works. I can't figure out what is wrong with my function below.

void sortAlphabetical(ElementType elements[NUM_ELEMENTS])
{
   printf("SORTING!\n");
   int c, d;
   for (c = 0 ; c < NUM_ELEMENTS - 1; c++)
   {
       for (d = 0 ; d < NUM_ELEMENTS - c - 1; d++)
       {
           if (elements[d].Name > elements[d+1].Name)
           {
                ElementType temp;

                temp.AtomicNumber = elements[d].AtomicNumber;
                strcpy(temp.Name, elements[d].Name);
                strcpy(temp.Symbol, elements[d].Symbol);

                elements[d].AtomicNumber = elements[d+1].AtomicNumber;
                strcpy(elements[d].Name, elements[d+1].Name);
                strcpy(elements[d].Symbol, elements[d+1].Symbol);

                elements[d+1].AtomicNumber = temp.AtomicNumber;
                strcpy(elements[d+1].Name, temp.Name);
                strcpy(elements[d+1].Symbol, temp.Symbol);
           }
       }
   }
}

Upvotes: 0

Views: 52

Answers (1)

aschepler
aschepler

Reputation: 72431

if (elements[d].Name > elements[d+1].Name)

C's > operator isn't "smart" enough to compare strings in dictionary order; it's only for numbers or pointers. This condition actually just compares the char* pointers to the names' first characters.

Instead you would need the strcmp function:

if (strcmp(elements[d].Name, elements[d+1].Name) > 0)

Also, instead of writing your own bubble sort, you might consider qsort, which is for exactly this sort of thing, is a bit easier to write, and may be faster for large arrays:

#include <stdlib.h>
#include <string.h>

int compareElementNames(const void* p1, const void* p2)
{
    const ElementType *elem1 = p1;
    const ElementType *elem2 = p2;
    return strcmp(elem1->Name, elem2->Name);
}

void sortAlphabetical(ElementType elements[NUM_ELEMENTS])
{
    qsort(elements, NUM_ELEMENTS, sizeof(*elements), compareElementNames);
}

Upvotes: 5

Related Questions