刚刚学习c++模板,试着写了几个程序:
#include <iostream>
using namespace std;
template <typename T>
class Sort
{
private:
int length;
T * array;
public:
Sort(int size);
void initArray();
void dispArray();
void insertSort();
void mergeSort(int p,int r);
void merge(int p,int q,int r);
};
template <typename T>
Sort<T>::Sort(int size=10):length(size)
{
array = new T [length];
}
template <typename T>
void Sort<T>::initArray()
{
for(int i=0;i<length;i++)
cin>>array[i];
}
template <typename T>
void Sort<T>::dispArray()
{
for(int i=0;i<length;i++)
cout<<array[i]<<" ";
cout<<endl;
}
template <typename T>
void Sort<T>::insertSort()
{
//T *tempArray = new T [length];
int j = 0;
T temp;
for(int i=1;i<length;i++)
{
temp = array[i];
for(j=i-1;j>=0;j--)
{
if(temp<array[j])
array[j+1] = array[j];
else
break;
}
array[j+1] = temp;
}
}
template <typename T>
void Sort<T>::merge(int low,int mid,int high)
{
int len1 = low;
int len2 = mid + 1;
T *temp = new T [high+1];
int k=0;
while (len1<=mid && len2 <= high)
{
if(array[len1]<array[len2])
temp[k++] = array[len1++];
else
temp[k++] = array[len2++];
}
while (len1<=mid)
temp[k++] = array[len1++];
while (len2<=high)
temp[k++] = array[len2++];
for(int i=low,j=0;i<=high;i++,j++)
array[i] = temp[j];
//cout<<temp[j]<<" ";
}
template <typename T>
void Sort<T>::mergeSort(int low,int high)
{
int mid;
if (low<high)
{
mid = (low + high)/2;
mergeSort(low,mid);
mergeSort(mid+1,high);
merge(low,mid,high);
}
}
int main()
{
int size;
cout<<"input the number the of array :";
cin>>size;
Sort<int> is(size);
is.initArray();
is.dispArray();
is.insertSort();
is.dispArray();
cout<<"input the number the of array second:";
cin>>size;
Sort<int> ms(size);
ms.initArray();
ms.dispArray();
ms.mergeSort(0,size-1);
ms.dispArray();
return 0;
}