Download demo project - 14 Kb
<!-- Article Starts -->
is part of the C and C++ language. It is a quick sort algorithm that
is both fast and easy to implement. It is a recursive algorithm, but it is
surprising fast. (30,000 items in about a fourth of a second on a PII-333
This 'How To' demonstrates the use of
qsort on a
However, it would work just as well on any other sequential data structure. Static arrays,
CPtrArray or something of your own creation.
The demo project is written in VC 5.0. It has not been plagiarized from any other
source. There are no restrictions on the source.
Suppose you wanted to store and sort number of items of type
defined as follows:
CArray template class we can store the
objects using the following array declaration
typedef CArray<CArrayClass, CArrayClass&> Type_aCArrayClass;
qsort you need to declare a callback function whose
address is known at compile time - meaning it must either be a global or
static function. The
qsort callback function must be defined
int (__cdecl *compare )(const void *elem1, const void *elem2 )
Items elem1 and elem2 are pointers to two items in the
array, and must be cast to the appropriate type and compared. The return
value of the function is as follows:
||elem1 less than elem2|
||elem1 equivalent to elem2|
||elem1 greater than elem2|
In our case the callback function would look like the following:
int CCArrayExampleDlg::SortTheArray(void* p1,void* p2)
CArrayClass* a1 = (CArrayClass*)p1;
CArrayClass* a2 = (CArrayClass*)p2;
if (a1->m_strMsgType <a2->m_strMsgType) n = -1;
elseif (a1->m_strMsgType >a2->m_strMsgType)
n = 1;
elseif(a1->m_wMsgId <a2->m_wMsgId) n = -1;
n = 1;
To use this sort callback we need to fill the array, call
and then display the results.
if(m_aCArrayClass.GetSize() > 0)
(int(*)(const void*, const void*))CCArrayExampleDlg::SortTheArray);
Chris is the Co-founder, Administrator, Architect, Chief Editor and Shameless Hack who wrote and runs The Code Project. He's been programming since 1988 while pretending to be, in various guises, an astrophysicist, mathematician, physicist, hydrologist, geomorphologist, defence intelligence researcher and then, when all that got a bit rough on the nerves, a web developer. He is a Microsoft Visual C++ MVP both globally and for Canada locally.
His programming experience includes C/C++, C#, SQL, MFC, ASP, ASP.NET, and far, far too much FORTRAN. He has worked on PocketPCs, AIX mainframes, Sun workstations, and a CRAY YMP C90 behemoth but finds notebooks take up less desk space.
He dodges, he weaves, and he never gets enough sleep. He is kind to small animals.
Chris was born and bred in Australia but splits his time between Toronto and Melbourne, depending on the weather. For relaxation he is into road cycling, snowboarding, rock climbing, and storm chasing.