template<class T>
class SequentialList
{
protected:
static const int m_InitLength = 100;
static const int m_IncreasLength = 10;
int m_Count;//元素个数
int m_BufLength;//数组长度
T* m_pBuf;//数据缓冲区
public:
SequentialList(void);
~SequentialList(void);
void Add(T Item);
void Display();
void SortBuf();//冒泡排序
int Sort1(int m_low,int m_high);
void Sort2(int m_low,int m_high);//快速排序
void QSort();//调用快速排序
void SelectSort();//选择排序
};
template<class T>
SequentialList<T>::SequentialList(void)
{
m_pBuf = new T[m_InitLength];
m_Count = 0;
m_BufLength = 100;
}
template<class T>
SequentialList<T>::~SequentialList(void)
{
if(m_pBuf != NULL)
{
delete []m_pBuf;
m_pBuf = NULL;
}
}
template<class T>
void SequentialList<T>::Add(T Item)
{
if(m_Count < m_BufLength)
{
m_pBuf[m_Count] = Item;
}
else
{
T* temp = new T[m_BufLength + m_IncreasLength];
for(int i = 0;i < m_Count;i++)
{
temp[i] = m_pBuf[i];
}
delete[] m_pBuf;
temp[m_Count] = Item;
m_pBuf = temp;
temp = NULL;
m_BufLength+=m_IncreasLength;
}
m_Count++;
}
template<class T>
void SequentialList<T>::Display()
{
for(int i = 0;i < m_Count;i++)
{
cout<<m_pBuf[i]<<endl;
}
}
//冒泡排序
template<class T>
void SequentialList<T>::SortBuf()
{
for(int i = 0;i < m_Count;i++)
{
for(int j = 0;j < m_Count - i-1;j++)
{
if(m_pBuf[j] > m_pBuf[j+1])
{
T temp = m_pBuf[j];
m_pBuf[j] = m_pBuf[j+1];
m_pBuf[j+1] = temp;
}
}
}
}
//快排算法
template<class T>
int SequentialList<T>::Sort1(int m_low,int m_high)
{
int low = m_low;
int high = m_high -1;
T pivotkey = m_pBuf[low];
while(low < high)
{
while((low < high)&&(m_pBuf[high] > pivotkey))
{
high--;
}
m_pBuf[low] = m_pBuf[high];
while((low < high)&&(m_pBuf[low] < pivotkey))
{
low++;
}
m_pBuf[high] = m_pBuf[low];
}
m_pBuf[low] = pivotkey;
return low;
}
//递归调用快排算法
template<class T>
void SequentialList<T>::Sort2(int m_low,int m_high)
{
int pivotkey;
if(m_low < m_high)
{
pivotkey = Sort1(m_low,m_high);
Sort2(m_low,pivotkey-1);
Sort2(pivotkey+1,m_high);
}
}
//对类内元素进行排序
template<class T>
void SequentialList<T>::QSort()
{
Sort2(0,m_Count-1);
}
//选择排序
template<class T>
void SequentialList<T>::SelectSort()
{
for(int i = 0;i < m_Count;i++)
{
int m_Number = i;
T temp1 = m_pBuf[i];
for(int j = i +1;j < m_Count;j++)
{
if(temp1 > m_pBuf[j])
{
temp1 = m_pBuf[j];
m_Number = j;
}
}
T temp2 = m_pBuf[i];
m_pBuf[i] = m_pBuf[m_Number];
m_pBuf[m_Number] = temp2;
}
}