Quantcast
Viewing all articles
Browse latest Browse all 2

Answer by Jonathan Leffler for Implement a bubble sort for an array of structs

You should use structure assignments because they are radically more compact than repeated assignments for each element of the structure. Like this:

struct Record
{
    int seqnum;
    int threat;
    int addrs[2];
    int ports[2];
    char dns_name[32];
};

void bubblesort(struct Record *ptr, int records,
                int (*fcomp)(const void *, const void *))
{
    int swapped;
    do
    {
        swapped = 0;
        for (int i = 0; i < records - 1; i++)
        {
            if (fcomp(ptr + i, ptr + i + 1) > 0)
            {
                swapped = 1;
                struct Record tmp = ptr[i];
                ptr[i] = ptr[i + 1];
                ptr[i + 1] = tmp;
            }
        }
    } while (swapped != 0);
}

Note that in this code, the temporary value tmp is a structure, not a pointer to a structure.

You also omitted the while (swapped != 0); condition and the trailing } in the code in the question. I've put them in by inference. That code compiles. I've not run it — I've merely reduced the swapping code to 3 lines from 21 or so.


Viewing all articles
Browse latest Browse all 2

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>