Search code examples
csortingstructbubble-sort

trying to sort structures but errors or crashing


I am coding a program which will sort the outputs by employee number, from lowest to highest. When I try and use the struct name in front of the temp variable it just says 'unknown type name strPerson'. I'm not too sure what I need to do, and I have only passed the pointer as a parameter as the other values can be retrieved from members within the struct as shown by the if statement.


Solution

  • When I try and use the struct name in front of the temp variable it just says 'unknown type name strPerson'

    There is no type strPerson. There is type struct strPerson. So the compiler issues an error for the declaration

    strPerson temp = ptrPerson[nCount + 1];
    

    You should write at least

    struct strPerson temp = ptrPerson[nCount + 1];
    

    Also the variable nCount was not initialized. So the function has undefined behavior.

    It is not clear what the magic number 5 means. If it is the size of the passed to the function array then again the function has undefined behavior because the expression nCount + 1 can be out of the range of valid indices for the array.

    The function itself should be declared like

    void fnEmployeeNumSort( struct strPerson *ptrPerson, size_t n );
    

    where the second parameter n specifies the size of the sorted sequence.

    And at last the function does not perform sorting. The sorting algorithm is implemented incorrectly.

    Here is a demonstrative program that shows how the function can implement the bubble sort algorithm.

    #include <stdio.h>
    
    struct strPerson
    {
        int nEmployeeNum;
    };
    
    void fnEmployeeNumSort( struct strPerson *ptrPerson, size_t n )
    {
        for ( size_t last = n; !( n < 2 ); n = last )
        {
            for ( size_t i = last = 1; i < n; i++ )
            {
                if ( ptrPerson[i].nEmployeeNum < ptrPerson[i - 1].nEmployeeNum )
                {
                    struct strPerson temp = ptrPerson[i];
                    ptrPerson[i] = ptrPerson[i - 1];
                    ptrPerson[i - 1] = temp;
                    last = i;
                }
            }
        }       
    }
    
    #define N   5
    
    int main(void) 
    {
        struct strPerson p[N] = { { 5 }, { 4 }, { 3 }, { 2 }, { 1 } };
    
        for ( size_t i = 0; i < N; i++ ) printf( "%d ", p[i].nEmployeeNum );
        putchar( '\n' );
    
        fnEmployeeNumSort( p, N );
    
        for ( size_t i = 0; i < N; i++ ) printf( "%d ", p[i].nEmployeeNum );
        putchar( '\n' );
    
        return 0;
    }
    

    The program output is

    5 4 3 2 1 
    1 2 3 4 5