Using Quicksort on a microcontroller

Sorting algorithms get more than their fair share of attention in Computer Science programs, yet they are just one of many tools that we use in firmware development. Recently I needed to sort an array of numbers on a small microcontroller and found quicksort easy to use and efficient. Quicksort is included in the standard library (stdlb.h) but you need to define the comparator.

First, create the comparator function.:

#include "stdlib.h"

int comp(const void * a, const void * b)
{
int* aa = (int*) a;
int* bb = (int*) b;
if (*aa==*bb)
return 0;
else
if (*aa < *bb)
return -1;
else
return 1;
}

Next, the arguments for qsort are:
a) the array to sort
b) The number of elements to sort (starting from the element at index==0 in the array)
c) The size (in bytes) of what you are sorting
d) the comparison function you wish to use.
See the following example:

void testSort()
{
int numbers[]={1892,45,200,-98,-4,5,-123,107,88,-1000};
printf("Before sorting: ");
for (int i=0;i<9;i++)
printf(" %d ",numbers[ i ]) ;
qsort(numbers,10,sizeof(int),comp) ;
printf("\r\nAfter sorting: ");
for (int i=0;i<9;i++)
printf(" %d ",numbers[ i ]) ;
printf("\r\n");
}

Derek Smith