1.二分搜素算法的递归实现
代码:
/*二分搜索递归算法*/
#include<iostream>
using namespace std;
int BinSearch(int a[],int low,int high,int key)
{
if(low>high)
{
return -1;//查找失败,返回-1;
}
else
{
int middle;
middle=(low+high)/2;
if(a[middle]==key)
{
return middle;//查找成功。
}
else
{
if(a[middle]>key)
BinSearch(a,low,middle-1,key);
else BinSearch(a,middle+1,high,key);
}
}
}
int main(){
int n;
cin>>n;
int *a=new int[n];
for(int i=0;i<n;i++)
cin>>a[i];
int key;
cin>>key;
cout<<BinSearch(a,0,n-1,key)<<endl;
system("pause");
return 0;
}
2.合并排序的递归算法实现
代码:
/*合并排序递归算法*/
#include<iostream>
using namespace std;
void Merge(int a[],int b[],int low,int middle,int high)
{
int i=low;
int j=middle+1;
int k=0;
while(i<=middle && j<=high)
{
if(a[i]<=a[j])b[k++]=a[i++];
else b[k++]=a[j++];//比较大小;
}
while(i<=middle)
b[k++]=a[i++];
while(j<=high)
b[k++]=a[j++];
for(int i=0;i<k;i++)
a[low+i]=b[i]; //将排好序的数组b在赋值回数组a中;
}
void MergeSort(int a[],int b[],int low,int high)
{
if(low<high)
{
int middle=(low+high)/2;
/*---分治思想---*/
//划分数组
MergeSort(a,b,low,middle);
MergeSort(a,b,middle+1,high);
//数组排序整合;
Merge(a,b,low,middle,high);
}
}
int main(){
int n;
cin>>n;
int *a=new int[n];
int *b=new int[n];
for(int i=0;i<n;i++)
cin>>a[i];
MergeSort(a,b,0,n-1);
for(int i=0;i<n;i++)
cout<<a[i]<<" ";
cout<<endl;
system("pause");
return 0;
}
3.快速排序的递归算法
代码:
/*快速排序递归算法*/
#include<iostream>
using namespace std;
int Partion(int a[],int low,int high)
{
int &key=a[low];
while(low<high)
{
while(low<high && a[high]>=key)
{
high--;
}
while(low<high && a[low]<=key)
{
low++;
}
swap(a[low],a[high]);
}
swap(a[low],key);
return low;
}
void QuickSort(int a[],int low,int high)
{
if(low<high)
{
int i=Partion(a,low,high);
QuickSort(a,low,i-1);
QuickSort(a,i+1,high);
}
}
int main(){
int n;
cin>>n;
int *a=new int [n];
for(int i=0;i<n;i++)
cin>>a[i];
QuickSort(a,0,n-1);
for(int i=0;i<n;i++)
cout<<a[i]<<" ";
cout<<endl;
system("pause");
return 0;
}
到此,递归与分治的6个基本问题就结束啦。