| 1 |
#pragma once |
| 2 |
|
| 3 |
////////////////////////////////////////////////////////////////////////// |
| 4 |
|
| 5 |
template <class TYPE, class ARG_TYPE = TYPE> |
| 6 |
class CSortArray : public CArray <TYPE, ARG_TYPE> |
| 7 |
{ |
| 8 |
public: |
| 9 |
CSortArray() {} |
| 10 |
virtual ~CSortArray() {} |
| 11 |
|
| 12 |
void QuickSort(BOOL bAscending = TRUE); |
| 13 |
|
| 14 |
protected: |
| 15 |
BOOL doQuickSort(TYPE *pArr, int nSize, BOOL bAscending = TRUE); |
| 16 |
void doQuickSortRecursive(TYPE *pArr, int d, int h, BOOL bAscending); |
| 17 |
}; |
| 18 |
|
| 19 |
////////////////////////////////////////////////////////////////////////// |
| 20 |
|
| 21 |
template <class TYPE, class ARG_TYPE> |
| 22 |
inline void CSortArray<TYPE, ARG_TYPE>::doQuickSortRecursive(TYPE *pArr, int d, int h, BOOL bAscending) |
| 23 |
{ |
| 24 |
int i, j, pvt; |
| 25 |
TYPE src, tmp; |
| 26 |
|
| 27 |
i = h; |
| 28 |
j = d; |
| 29 |
pvt = static_cast<UINT>((d + h) / 2); |
| 30 |
src = pArr[pvt]; |
| 31 |
|
| 32 |
do |
| 33 |
{ |
| 34 |
if (bAscending) |
| 35 |
{ |
| 36 |
while (pArr[j] < src) j++; |
| 37 |
while (pArr[i] > src) i--; |
| 38 |
} |
| 39 |
else |
| 40 |
{ |
| 41 |
while (pArr[j] > src) j++; |
| 42 |
while (pArr[i] < src) i--; |
| 43 |
} |
| 44 |
|
| 45 |
if (i >= j) |
| 46 |
{ |
| 47 |
|
| 48 |
if (i != j) |
| 49 |
{ |
| 50 |
tmp = pArr[i]; |
| 51 |
pArr[i] = pArr[j]; |
| 52 |
pArr[j] = tmp; |
| 53 |
|
| 54 |
} |
| 55 |
|
| 56 |
i--; |
| 57 |
j++; |
| 58 |
} |
| 59 |
} |
| 60 |
while (j <= i); |
| 61 |
|
| 62 |
if (d < i) doQuickSortRecursive(pArr, d, i, bAscending); |
| 63 |
if (j < h) doQuickSortRecursive(pArr, j, h, bAscending); |
| 64 |
} |
| 65 |
|
| 66 |
////////////////////////////////////////////////////////////////////////// |
| 67 |
|
| 68 |
template <class TYPE, class ARG_TYPE> |
| 69 |
inline BOOL CSortArray<TYPE, ARG_TYPE>::doQuickSort(TYPE *pArr, int nSize, BOOL bAscending) |
| 70 |
{ |
| 71 |
BOOL rc = TRUE; |
| 72 |
int low, high; |
| 73 |
|
| 74 |
if (nSize > 1) |
| 75 |
{ |
| 76 |
try |
| 77 |
{ |
| 78 |
low = 0; |
| 79 |
high = nSize - 1; |
| 80 |
|
| 81 |
doQuickSortRecursive(pArr, low, high, bAscending); |
| 82 |
} |
| 83 |
catch (...) |
| 84 |
{ |
| 85 |
::SetLastError(ERROR_INVALID_PARAMETER); |
| 86 |
rc = FALSE; |
| 87 |
} |
| 88 |
} |
| 89 |
else |
| 90 |
{ |
| 91 |
::SetLastError(ERROR_INVALID_PARAMETER); |
| 92 |
rc = FALSE; |
| 93 |
} |
| 94 |
|
| 95 |
return rc; |
| 96 |
} |
| 97 |
|
| 98 |
////////////////////////////////////////////////////////////////////////// |
| 99 |
|
| 100 |
template <class TYPE, class ARG_TYPE> |
| 101 |
inline void CSortArray<TYPE, ARG_TYPE>::QuickSort(BOOL bAscending/* = TRUE*/) |
| 102 |
{ |
| 103 |
if (GetSize() > 1) |
| 104 |
{ |
| 105 |
doQuickSort(GetData(), GetSize(), bAscending); |
| 106 |
} |
| 107 |
} |
| 108 |
|
| 109 |
////////////////////////////////////////////////////////////////////////// |