Search code examples
csortingbubble-sort

Can someone help me what's wrong with this bubble sort?


sort.hpp -> we sort station names

    struct _element {
    char icao_code[5];
    char station_name[100];
};

typedef struct _element element;

void bubbleSort(element* stations, int size);

bubblesort (doesn't work)

void bubbleSort(element *pElement, int size) {
int i, j;
for (i = 0; i < size - 1; i++)

    // Last i elements are already in place
    for (j = 0; j < size - i - 1; j++)
        if (pElement[j].station_name > pElement[j + 1].station_name)
        {
            element tmp = pElement[j];
            pElement[j] = pElement[i];
            pElement[i] = tmp;
        }
}

Does someone know how to make this code work?


Solution

  • This is not the correct way to compare C strings

    if (pElement[j].station_name > pElement[j + 1].station_name)
    

    The problem is that you are comparing the pointers, not the characters that are pointed at.

    Use strcmp instead

    if (strcmp(pElement[j].station_name, pElement[j + 1].station_name) > 0)