Sorted MFC CArray

UPDATE: New version of this class is available here.

On a project I work in my spare time. I needed a quick way of sorting elements stored in CArray so CSortArray was born. It does nothing special. It extends the CArray class providing one public method named QuickSort who uses the qsort CRT function to do the sorting. Providing the right Compare function you can sort any type of array.

Below is the CSortArray class:

1
2
3
4
5
6
7
8
9
10
template <class TYPE, class ARG_TYPE = const TYPE&> class CSortArray : public CArray<TYPE, ARG_TYPE>
{
// Public member functions
public:
 
	void QuickSort( int (__cdecl *compare )(const void*, const void*) )
	{
		qsort( m_pData, GetCount(), sizeof(TYPE), (*compare) );
	}
};

The QuickSort member takes an address of user defined comparison function with the following declaration:

1
int Compare( const void* pElement1, const void* pElement2 );

where pElement1 is the first element used in the compare process and pElement2 is the second.

Your function must compare the elements and return one of the following:

  • < 0 if pElement1 is less than pElement2
  • 0 if pElement1 is equal to pElement2
  • > 0 if pElement1 is greater than pElement2

Below is an example usage of the CSortArray class:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
// User defined Compare function
int Compare( const void* element1, const void* element2 )
{
	int *pElem1 = (int*) element1;
	int *pElem2 = (int*) element2;
 
	if( *pElem1 < *pElem2 )
	{
		return -1;
	} else if ( *pElem1 == *pElem2 ) {
		return 0;
	} else {
		return 1;
	}
 
	return 0;
}
 
// Application entry point
int _tmain(int argc, TCHAR* argv[], TCHAR* envp[])
{
        // SortArray usage
	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;
}

In the CSortArray class we can also implement a search method, but that’s a theme of another post.

If you liked this article and think it is useful use the buttons below.

Leave a Reply

Your email address will not be published. Required fields are marked *

*