合併排序和快排及改進快排
template<class T>
class SortableList
{
public:
SortableList(int mSize)
{
maxSize=mSize;
l=new T[maxSize];
n=0;
}
~SortableList()
{
delete []l;
}
void Input();//輸入
void Output();
void MergeSort();//合併排序
void QuickSort();//快排
private:
int maxSize;
int n;
T *l;
void MergeSort(int left,int right);//合併排序
void Merge(int left,int mid,int right);//將兩個有序序列合併成一個有序序列,時間複雜度爲O(n)
void Swap(int i,int j);
void QuickSort(int left,int right);
int Partition(int left,int right);
int RandomPartition(int left,int right);
};
template<class T>
void SortableList<T>::Input()
{
int m;
cout<<"輸入這個序列的個數"<<endl;
cin>>m;
n=m;
T *ll=new T[n];
cout<<"輸入序列"<<endl;
for(int i=0;i<n;i++)
{
cin>>ll[i];
l[i]=ll[i];
}
}
template<class T>
void SortableList<T>::Output()
{
cout<<"排序的結果是"<<endl;
for(int i=0;i<n;i++)
{
cout<<l[i]<<" ";
}
cout<<endl;
}
template<class T>
void SortableList<T>::Swap(int i,int j)
{
T temp;
temp=l[i];
l[i]=l[j];
l[j]=temp;
}
template<class T>
void SortableList<T>::MergeSort()
{
MergeSort(0,n-1);
}
template<class T>
void SortableList<T>::MergeSort(int left,int right)
{
if(left<right)
{
int mid=(left+right)/2;
MergeSort(left,mid);
MergeSort(mid+1,right);
Merge(left,mid,right);
}
}
template<class T>
void SortableList<T>::Merge(int left,int mid,int right)
{
T* temp=new T[right-left+1];
int i=left,j=mid+1,k=0;
while((i<=mid)&&(j<=right)){
if(l[i]<=l[j]) temp[k++]=l[i++];
else temp[k++]=l[j++];
}
while(i<=mid)
{
temp[k++]=l[i++];
// cout<<temp[k-1];
}
while(j<=right)
temp[k++]=l[j++];
for(i=0,k=left;k<=right; ) l[k++]=temp[i++];
delete []temp;
}
template<class T>
void SortableList<T>::QuickSort()
{
QuickSort(0,n-1);
}
template<class T>
void SortableList<T>::QuickSort(int left,int right)
{
if(left<right)
{
int j=Partition(left,right);
//int j=RandomPartition(left,right);
QuickSort(left,j-1);
QuickSort(j+1,right);
}
}
template<class T>
int SortableList::RandomPartition(int left,int right)
{
srand((unsigned)time(NULL));
int i=rand()%(right-left)+left;
Swap(i,left);
return Partition(left,right);
}
template<class T>
int SortableList<T>::Partition(int left,int right)
{
int i=left,j=right+1;
do{
do i++; while(l[i]<l[left]);
do j--; while(l[j]>l[left]);
if(i<j)
{
Swap(i,j);
}
}while(i<j);
Swap(left,j);
return j;
}
測試函數
#include<iostream>
using namespace std;
#include"sortedable.h"
int main()
{
SortableList<int> *s=new SortableList<int>(50);
char c;
menu:cout<<"**************1,合併排序************"<<endl;
cout<<"**************2,快速排序************"<<endl;
cout<<"**************0,退出 ************"<<endl;
cin>>c;
switch(c)
{
case '1':
s->Input();
s->MergeSort();
s->Output();
goto menu;
break;
case '2':
s->Input();
s->QuickSort();
s->Output();
goto menu;
break;
case '0':
break;
default:
cout<<"輸入錯誤"<<endl;
goto menu;
break;
}
return 0;
}