递归与分治策略
-
二分搜索算法是运用分治策略的典型例子。二分搜索算法的基本思想是将n个元素分成个数大致相同的两半。取a(n/2)与x做比较。如果x=a(n/2),则找到x算法终止。如果x小于它,则只在数组a的左半部继续搜索x。如果x大于它,则指代数组a的右半部,继续搜索x,具体的C++算法可描述如下。
-
合并排序算法是用分治策略实现对n个元素进行排序的算法,其基本思想是将待排序元素分成大小。大致相同的两个子集合,分别对两个子集合进行排序,最终将排好序的子集和合并成要求的排好序的集合。
-
快速排序算法是基于分治策略的另一个排序算法
-
线时间选择实际上是模仿快速排序算法设计出来的基本思想,也是对输入速度进行递归划分。
。
using namespace std;
//二分搜索
template<class Type>
int BinarySearch(Type a[],const Type& x,int n){
int left= 0;
int right = n-1;
while(left<=right){
int middle =(left+right)/2;
if(x==a[middle])
return middle;
if(x>a[middle])
left=middle+1;
else
right=middle-1;
}
return -1;
}
//合并排序
template<class Type>
void Merge(Type c[],Type d[],int l,int m,int r){
int i =l,j= m+1,k=l;
while((i<=m)&&(j<=r)){
if(c[i]<=c[j])
d[k++]=c[i++];
else
d[k++]=c[j++];
}
if(i>m){
for(int q=j;q<=r;q++)
d[k++]=c[q];
}
else{
for(int q=i;q<=m;q++)
d[k++]=c[q];
}
}
template<class Type>
int Copy(Type a[],Type b[],int left,int right){
for(int i=left;i<=right;i++){
a[i]=b[i];
}
}
template<class Type>
void MergeSort(Type a[],int left,int right){
if(left<right){
int i=(left+right)/2;
MergeSort(a,left,i);
MergeSort(a,i+1,right);
int b[4];
Merge(a,b,left,i,right);
Copy(a,b,left,right);
}
}
//快速排序
template<class T>
void Swap(T & a,T & b){
T temp=a;
a=b;
b=temp;
}
template<class Type>
int Partition(Type a[],int p,int r){
int i = p,j=r+1;
Type x=a[p];
while(true){
while(a[++i]<x&&i<r);
while(a[--j]>x);
if(i>=j)
break;
Swap(a[i],a[j]);
}
a[p] =a[j];
a[j]=x;
return j;
}
template<class Type>
void QuickSort(Type a[],int p,int r){
if(p<r){
int q = Partition(a,p,r);
QuickSort(a,p,q-1);
QuickSort(a,q+1,r);
}
}
//线性时间选择
template<class Type>
Type Select(Type a[],int p,int r,int k){
if(p==r)
return a[p];
int i=Partition(a,p,r);
int j;
j=i-p+1;
if(k<=j)
return Select(a,p,i,k);
else
return Select(a,i+1,r,k-j);
}
#endif // LIANGHELONG1_H_INCLUDED
using namespace std;
int main()
{
cout <<"二分搜索排序"<<" ";
int a[9]={1,2,3,4,5,6,7,8,9};;
const int x=4;
int m =BinarySearch(a,x,9);
cout<<m<<endl;
cout<<" "<<endl;
cout<<"合并排序"<<" ";
int b[4]={4,3,2,1};
MergeSort(a,0,3);
for(int j=0;j<4;j++){
cout<<a[j]<<" ";
}
cout<<" "<<endl;
cout<<"快速排序"<<" ";
int c[4]={4,3,2,1};
QuickSort(a,0,3);
for(int i=0;i<4;i++){
cout<<a[i]<<" ";
}
cout<<" "<<endl;
cout<<"线性时间搜索"<<" ";
int d[4]={2,1,3,4};
cout<<Select(d,0,3,2)<<endl;
return 0;
}