# CSortArray updated

*2012-02-14*

> An updated CSortArray template for MFC, adding binary search and context pointers for sorting and searching structured records.

This is an update to the [CSortArray class](/sorted-mfc-carray/) I wrote a few weeks ago. This version extends its sorting functionality and adds binary search.

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

/// Extends CArray with sorting and binary search.
template <class TYPE, class ARG_TYPE = const TYPE&>
class CSortArray : public CArray<TYPE, ARG_TYPE>
{
public:
    /// Sorts the array using a comparison function.
    void QuickSort(int (__cdecl *compare)(const void*, const void*))
    {
        qsort(this->m_pData, this->GetCount(), sizeof(TYPE), compare);
    }

    /// Sorts the array using a comparison function and a context pointer.
    void QuickSort(int (__cdecl *compare)(void*, const void*, const void*), void* context)
    {
        qsort_s(this->m_pData, this->GetCount(), sizeof(TYPE), compare, context);
    }

    /// Finds an element in the sorted array.
    TYPE* Search(const TYPE& oKey, int (__cdecl *compare)(const void*, const void*))
    {
        return static_cast<TYPE*>(bsearch(&oKey, this->m_pData, this->GetCount(), sizeof(TYPE), compare));
    }

    /// Finds an element using a comparison function and a context pointer.
    TYPE* Search(const TYPE& oKey, int (__cdecl *compare)(void*, const void*, const void*), void* context)
    {
        return static_cast<TYPE*>(bsearch_s(&oKey, this->m_pData, this->GetCount(), sizeof(TYPE), compare, context));
    }
};
```

The new `QuickSort()` overload accepts a context pointer. The comparison function can use this context to choose which field to compare. This is useful when sorting records such as localities, which contain city, county, and community names:

```cpp
#define SIZE_CITY_NAME 49
#define SIZE_COUNTY_NAME 49
#define SIZE_COMMUNITY_NAME 49

typedef struct LOCALITY
{
    int nId;
    TCHAR szCity[SIZE_CITY_NAME + 1];
    TCHAR szCommunity[SIZE_COMMUNITY_NAME + 1];
    TCHAR szCounty[SIZE_COUNTY_NAME + 1];
    int nContactsCount;

    LOCALITY()
    {
        ::ZeroMemory(this, sizeof(*this));
    }
} LOCALITY;
```

The comparison function for this overload has the following signature:

```cpp
int (__cdecl *compare)(void*, const void*, const void*);
```

The first argument receives the context pointer passed to `QuickSort()` or `Search()`.

The `Search()` method also has overloads with and without a context pointer. It returns a pointer to a matching element, or `NULL` if no match is found.

The following Unicode MFC console example sorts the localities by ID, contact count, and city name in separate passes, then searches for a city by name:

```cpp
// SortArrayApp.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include "SortArrayApp.h"
#include "SortArray.h"

#ifdef _DEBUG
#define new DEBUG_NEW
#endif

// The one and only application object
CWinApp theApp;

using namespace std;

#define CONTEXT_ID 1
#define CONTEXT_CITY 2
#define CONTEXT_COMMUNITY 3
#define CONTEXT_COUNTY 4
#define CONTEXT_CONTACTS 5

#define SIZE_CITY_NAME 49
#define SIZE_COUNTY_NAME 49
#define SIZE_COMMUNITY_NAME 49

typedef struct LOCALITY
{
    int nId;
    TCHAR szCity[SIZE_CITY_NAME + 1];
    TCHAR szCommunity[SIZE_COMMUNITY_NAME + 1];
    TCHAR szCounty[SIZE_COUNTY_NAME + 1];
    int nContactsCount;

    LOCALITY()
    {
        ::ZeroMemory(this, sizeof(*this));
    }
} LOCALITY;

int Compare( void* context, const void* element1, const void* element2 )
{
    LOCALITY *pLocality1 = (LOCALITY*) element1;
    LOCALITY *pLocality2 = (LOCALITY*) element2;
    int *pContext = (int*) context;

    switch ( *pContext )
    {
    case CONTEXT_ID:
        {
            if ( pLocality1->nId > pLocality2->nId )
            {
                return 1;
            } else if ( pLocality1->nId < pLocality2->nId ) {
                return -1;
            } else if ( pLocality1->nId == pLocality2->nId ) {
                return 0;
            }
            break;
        }
    case CONTEXT_COMMUNITY:
        {
            return _tcscmp( pLocality1->szCommunity, pLocality2->szCommunity );
        }
    case CONTEXT_COUNTY:
        {
            return _tcscmp( pLocality1->szCounty, pLocality2->szCounty );
        }
    case CONTEXT_CITY:
        {
            return _tcscmp( pLocality1->szCity, pLocality2->szCity );
        }
    case CONTEXT_CONTACTS:
        {
            if ( pLocality1->nContactsCount > pLocality2->nContactsCount )
            {
                return 1;
            } else if ( pLocality1->nContactsCount < pLocality2->nContactsCount ) {
                return -1;
            } else if ( pLocality1->nContactsCount == pLocality2->nContactsCount ) {
                return 0;
            }
            break;
        }
    }

    return 0;
}

int _tmain(int argc, TCHAR* argv[], TCHAR* envp[])
{
    int nRetCode = 0;

    HMODULE hModule = ::GetModuleHandle(NULL);

    if (hModule != NULL)
    {
        // Initialize MFC and print an error on failure.
        if (!AfxWinInit(hModule, NULL, ::GetCommandLine(), 0))
        {
            // TODO: change error code to suit your needs
            _tprintf(_T("Fatal Error: MFC initialization failed\n"));
            nRetCode = 1;
        }
        else
        {
            // SortArray usage
            CSortArray<LOCALITY> arrToSort;

            // Add locality information to the array.
            LOCALITY recLocality;

            recLocality.nId = 2;
            _tcscpy_s( recLocality.szCity, ( SIZE_CITY_NAME + 1 ), _T("Varna") );
            _tcscpy_s( recLocality.szCommunity, ( SIZE_COMMUNITY_NAME + 1 ), _T("Varna") );
            _tcscpy_s( recLocality.szCounty, ( SIZE_COUNTY_NAME + 1 ), _T("Varna") );
            recLocality.nContactsCount = 10;
            arrToSort.Add( recLocality );

            recLocality.nId = 1;
            _tcscpy_s( recLocality.szCity, ( SIZE_CITY_NAME + 1 ), _T("Balgarene") );
            _tcscpy_s( recLocality.szCommunity, ( SIZE_COMMUNITY_NAME + 1 ), _T("Lovech") );
            _tcscpy_s( recLocality.szCounty, ( SIZE_COUNTY_NAME + 1 ), _T("Lovech") );
            recLocality.nContactsCount = 3;
            arrToSort.Add( recLocality );

            recLocality.nId = 4;
            _tcscpy_s( recLocality.szCity, ( SIZE_CITY_NAME + 1 ), _T("Veliko Turnovo") );
            _tcscpy_s( recLocality.szCommunity, ( SIZE_COMMUNITY_NAME + 1 ), _T("Turnovo") );
            _tcscpy_s( recLocality.szCounty, ( SIZE_COUNTY_NAME + 1 ), _T("Turnovo") );
            recLocality.nContactsCount = 8;
            arrToSort.Add( recLocality );

            recLocality.nId = 3;
            _tcscpy_s( recLocality.szCity, ( SIZE_CITY_NAME + 1 ), _T("Sofia") );
            _tcscpy_s( recLocality.szCommunity, ( SIZE_COMMUNITY_NAME + 1 ), _T("Sofia Grad") );
            _tcscpy_s( recLocality.szCounty, ( SIZE_COUNTY_NAME + 1 ), _T("Sofia") );
            recLocality.nContactsCount = 8;
            arrToSort.Add( recLocality );

            // Display the unsorted elements
            cout << "Unsorted elements:" << endl;
            cout << "ID\tCity\tCommunity\tCounty\tContacts" << endl;
            for ( int i = 0; i < arrToSort.GetCount(); i++ )
            {
                LOCALITY& currLocality = arrToSort[i];
                wcout << currLocality.nId << ".\t";
                wcout << currLocality.szCity << "\t";
                wcout << currLocality.szCommunity << "\t";
                wcout << currLocality.szCounty << "\t";
                wcout << currLocality.nContactsCount << endl;
            }
            wcout << endl;

            int context = CONTEXT_ID;

            // Sort the array by ID
            arrToSort.QuickSort( Compare, &context );

            cout << "Elements sorted by locality ID:" << endl;
            cout << "ID\tCity\tCommunity\tCounty\tContacts" << endl;
            for ( int i = 0; i < arrToSort.GetCount(); i++ )
            {
                LOCALITY& currLocality = arrToSort[i];
                wcout << currLocality.nId << ".\t";
                wcout << currLocality.szCity << "\t";
                wcout << currLocality.szCommunity << "\t";
                wcout << currLocality.szCounty << "\t";
                wcout << currLocality.nContactsCount << endl;
            }
            wcout << endl;

            // Sort the array by contacts count
            context = CONTEXT_CONTACTS;
            arrToSort.QuickSort( Compare, &context );

            cout << "Elements sorted by contacts count:" << endl;
            cout << "ID\tCity\tCommunity\tCounty\tContacts" << endl;
            for ( int i = 0; i < arrToSort.GetCount(); i++ )
            {
                LOCALITY& currLocality = arrToSort[i];
                wcout << currLocality.nId << ".\t";
                wcout << currLocality.szCity << "\t";
                wcout << currLocality.szCommunity << "\t";
                wcout << currLocality.szCounty << "\t";
                wcout << currLocality.nContactsCount << endl;
            }
            wcout << endl;

            // Sort the array by city name.
            context = CONTEXT_CITY;
            arrToSort.QuickSort( Compare, &context );

            cout << "Elements sorted by city name:" << endl;
            cout << "ID\tCity\tCommunity\tCounty\tContacts" << endl;
            for ( int i = 0; i < arrToSort.GetCount(); i++ )
            {
                LOCALITY& currLocality = arrToSort[i];
                wcout << currLocality.nId << ".\t";
                wcout << currLocality.szCity << "\t";
                wcout << currLocality.szCommunity << "\t";
                wcout << currLocality.szCounty << "\t";
                wcout << currLocality.nContactsCount << endl;
            }
            wcout << endl;

            // Searching by city name
            context = CONTEXT_CITY;
            LOCALITY recSearch;
            wcout << "Enter city name: ";
            wcin.getline(recSearch.szCity, SIZE_CITY_NAME + 1);

            LOCALITY *pResult = arrToSort.Search( recSearch, Compare, &context );
            if ( pResult )
            {
                wcout << pResult->nId << ".\t";
                wcout << pResult->szCity << "\t";
                wcout << pResult->szCommunity << "\t";
                wcout << pResult->szCounty << "\t";
                wcout << pResult->nContactsCount << endl;
            }
            else
            {
                wcout << recSearch.szCity << " not found!" << endl;
            }
        }
    }
    else
    {
        // TODO: change error code to suit your needs
        _tprintf(_T("Fatal Error: GetModuleHandle failed\n"));
        nRetCode = 1;
    }

    return nRetCode;
}
```

**Note:** `Search()` uses [`bsearch`](https://learn.microsoft.com/en-us/cpp/c-runtime-library/reference/bsearch) or [`bsearch_s`](https://learn.microsoft.com/en-us/cpp/c-runtime-library/reference/bsearch-s). Before searching, sort the array using the same comparison function and context as the search. A possible extension would be to track the array's current sort order.

