C++实现模板顺序表和三种排序方法
来源:互联网 发布:淘宝抢单 编辑:程序博客网 时间:2024/04/30 17:12
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;
}
}
- C++实现模板顺序表和三种排序方法
- c++(模板类)实现顺序表
- 【C++】用模板实现顺序表
- 【C++】用模板实现顺序表Vector
- 【C语言】冒泡法排序的三种实现方法
- 模板实现顺序表和链表
- 模板实现顺序表和单链表
- 模板实现顺序表和循环双链表
- 模板实现顺序表
- 模板实现顺序表
- 模板实现顺序表
- 模板实现顺序表
- c/c++之模板方法实现归并排序
- 顺序表增删改查两种方法---C实现
- [数据结构] 顺序表的实现(c++/类模板)
- 【C++】模板类顺序表
- 归并排序三种实现方法(递归、非递归和自然合并排序)
- 冒泡排序三种实现方法
- 新年第一篇
- hibernate笔记
- 3
- Java十大人物
- 4
- C++实现模板顺序表和三种排序方法
- 5
- 由一个DEBUG信息说开去
- Jsp连接MSSQL2000的两种方法
- 我的问题
- ExtJs学习笔记03
- hava a try
- Struts2——OGNL
- 这些问题你可以用一行代码可以搞定吗?