# Sorted MFC CArray

*2012-02-08*

> Sort MFC CArray elements with a CSortArray template that wraps qsort, including a custom comparison function and a complete C++ example.

**Update:** An [updated version of CSortArray](/csortarray-updated/) is now available.

While working on a project in my spare time, I needed a quick way to sort elements stored in an MFC [`CArray`](https://learn.microsoft.com/en-us/cpp/mfc/reference/carray-class). I wrote `CSortArray`, which extends `CArray` with a public `QuickSort()` method that uses the C runtime's [`qsort`](https://learn.microsoft.com/en-us/cpp/c-runtime-library/reference/qsort) function.

Here's the class:

```cpp
#include <afxtempl.h>
#include <stdlib.h>

template <class TYPE, class ARG_TYPE = const TYPE&>
class CSortArray : public CArray<TYPE, ARG_TYPE>
{
public:
    void QuickSort(int (__cdecl *compare)(const void*, const void*))
    {
        qsort(this->m_pData, this->GetCount(), sizeof(TYPE), compare);
    }
};
```

The `QuickSort()` method takes a pointer to a comparison function with this signature:

```cpp
int Compare(const void* pElement1, const void* pElement2);
```

`pElement1` and `pElement2` point to the two elements being compared. The function must return:

- A value less than `0` if `pElement1` is less than `pElement2`.
- `0` if the elements are equal.
- A value greater than `0` if `pElement1` is greater than `pElement2`.

Save the class in `SortArray.h`. The following MFC console example sorts an array of integers:

```cpp
#include "stdafx.h"
#include "SortArray.h"
#include <iostream>

using namespace std;

// Comparison function for integer elements.
int Compare(const void* element1, const void* element2)
{
    const int* pElem1 = static_cast<const int*>(element1);
    const int* pElem2 = static_cast<const int*>(element2);

    if (*pElem1 < *pElem2)
    {
        return -1;
    }
    else if (*pElem1 == *pElem2)
    {
        return 0;
    }
    else
    {
        return 1;
    }
}

// Application entry point.
int _tmain(int argc, TCHAR* argv[], TCHAR* envp[])
{
    CSortArray<int> arrToSort;

    // Add some unsorted elements to the array.
    arrToSort.Add(5);
    arrToSort.Add(2);
    arrToSort.Add(10);
    arrToSort.Add(17);
    arrToSort.Add(1);
    arrToSort.Add(8);
    arrToSort.Add(3);

    // Display the unsorted elements.
    cout << "Unsorted elements" << endl;
    for (int i = 0; i < arrToSort.GetCount(); i++)
    {
        cout << arrToSort[i] << endl;
    }

    // Sort the array.
    arrToSort.QuickSort(Compare);

    // Display the sorted elements.
    cout << "Sorted elements" << endl;
    for (int j = 0; j < arrToSort.GetCount(); j++)
    {
        cout << arrToSort[j] << endl;
    }

    return 0;
}
```

`CSortArray` could also provide a search method, but that's a topic for another post.

