An alternative to bubble sorting or insertion sorting, the QuickSort algorithm is accessible from either C or C++ and can be used with many data types.
Sorting is a useful programming exercise, and it is important to understand the various algorithms that can be used to sort a list of data. We shall be looking at the QuickSort algorithm, as implemented through a simple call in C and C++ to the qsort function.
The qsort function is available in the stdlib.h library, and requires:
Due to the fact that the quicksort algorithm implemented in the qsort function is designed to work with any data type, the programmer must provide in the call to the qsort function. This allows us to use any kind of simple or complex type, including linked lists.
The comparison function must return a specific set of values for the Quick Sort routine to be able to process the array (list) of values. The actual return logic is the same as for the string comparison function strcmp, namely:
If we implement, for example, a simple structure:
When we compare two sName items, we want to first position on the basis of the Last Name, and then on the First Name. Since the contents of the First Name only come into play of the Last Names are both the same, we cannot use a simple strcmp function call. So, we construct the following:
(There are better ways to do this, with less calls to strcmp, but this illustrates the point).
With our comparison function in hand, we could use it to implement a simple bubble sort. A bubble sort algorithm does the following:
This is performed until no more swaps are made, at which point the list is sorted. If we wanted to write slightly more accurate pseudocode, it would look like:
This will sort the names in descending order, as the ones that occur at the front of the alphabet are bubbled to the end of the list. If we wanted to sort in the other direction, we would test for equality with 1 and not -1.
From here it is a simple step to using the qsort function. All we need is an array of elements to sort:
We can then make a single call to quick sort:
This will sort the list, based on whatever we use in the CompareNames function as our sorting criteria.