南邮《算法设计与分析》第一次实验源码

来源:互联网 发布:网络剧题材分布 编辑:程序博客网 时间:2024/05/16 11:41

合并排序和快排及改进快排
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;}


	
				
		
原创粉丝点击