00001
00002
00003
00004
00005
00006
00007
00008
00009
00010
00011
00012 #ifndef TA_HEAPSORT_H
00013 #define TA_HEAPSORT_H
00014
00015 template <class Item>
00016 class HeapSort
00017 {
00018 public:
00019 static void DoHeapSort(Item* pList, int nSize)
00020 {
00021 HeapSort(pList, nSize);
00022 }
00023
00024 private:
00025
00026 Item* m_pList;
00027 int m_nSize;
00028
00029 HeapSort(Item* pList, int nSize)
00030 {
00031 m_pList = pList;
00032 m_nSize = nSize;
00033
00034
00035 for (int i = (m_nSize >> 1) - 1; i >= 0; i--)
00036 DownHeap(i);
00037
00038
00039 while (m_nSize > 1)
00040 {
00041 m_nSize--;
00042 Swap(0, m_nSize);
00043 DownHeap(0);
00044 }
00045 }
00046
00047 void DownHeap(int i)
00048 {
00049 int j = (i << 1) + 1;
00050 while (j < m_nSize)
00051 {
00052 if (j + 1 < m_nSize)
00053 {
00054 if (m_pList[j + 1].value > m_pList[j].value)
00055 j++;
00056 }
00057 if (m_pList[i].value >= m_pList[j].value)
00058 return;
00059 Swap(i, j);
00060 i = j;
00061 j = (i << 1) + 1;
00062 }
00063 }
00064
00065 void Swap(int i, int j)
00066 {
00067 Item tmpItem = m_pList[i];
00068 m_pList[i] = m_pList[j];
00069 m_pList[j] = tmpItem;
00070 }
00071 };
00072
00073
00074 #endif // TA_HEAPSORT_H
© Copyright 2004-2006 TRUE AXIS PTY LTD Australia. All rights reserved.