When programming in C for embedded systems where memory, disk usage and CPU usage are all very strict there are several ‘rules’ in place such as not use dynamically allocated arrays; this ensures that you can retain more control over memory management.

In a recent experience I had a fixed size array which was always populated below capacity, this array needed to be sorted which would normally leave my zero initialised elements at the start of my array and mess up my loop logic further on in the program.

I had an idea that I could use my sort comparison function to do two things – the first is the original sort purpose of ordering my elements, the second would be to move all unused elements to the end of the array.

Guess what, it’s very simple! I present the vinaigrette sort (so called because the oil and vinegar separate into layers in a vinaigrette).

It is as simple as modifying the compare function required by the qsort function. Check if a field in your struct (or your data) is zero and therefore unused and then declare it as ‘greater’ than any comparison. I did find that an older GCC version (3.7) required the line as described in the above source code, GCC 4.7 compiled and ran as required with just the one comparison.

Note the memset line, if you leave the array uninitialised then the compare won’t have anything defined to search for that would signify an unused element.