归并排序
#include <iostream>
using namespace std;
void Merge(int a[],int b[],int l,int m,int r)
{
int i=l,j=m+1,k=l;
while((i<=m)&&(j<=r))
{
if(a[i]<=a[j])
b[k++]=a[i++];
else
b[k++]=a[j++];
}
if(i>m)
{
for(int q=j;q<=r;q++)
b[k++]=a[q];
}
else
{
for(int q=i;q<=m;q++)
b[k++]=a[q];
}
for(i=l;i<=r;i++)
a[i]=b[i];
}
void mergesort(int a[],int b[],int l,int r)
{
if(l<r){
int m=(l+r)/2;
mergesort(a,b,l,m);
mergesort(a,b,m+1,r);
Merge(a,b,l,m,r);
}
}
int main()
{
int a[10]={3,5,2,7,8,1,9,0,13,41};
int b[10];
mergesort(a,b,0,9);
for(int i=0;i<10;i++)
cout<<a[i]<<" ";
cout<<endl;
return 0;
}
归并排序
#include <iostream>
using namespace std;
void Merge(int a[],int b[],int l,int m,int r)
{
int i=l,j=m+1,k=l;
while((i<=m)&&(j<=r))
{
if(a[i]<a[j])
b[k++]=a[i++];
else
b[k++]=a[j++];
}
if(i>m)
{
for(int q=j;q<=r;q++)
b[k++]=a[q];
}
else
{
for(int q=i;q<=m;q++)
b[k++]=a[q];
}
}
void mergepass(int a[],int b[],int s,int n)
{
int i=0;
while(i<=n-2*s)
{
Merge(a,b,i,i+s-1,i+2*s-1);
i=i+2*s;
}
if(i+s<n)
Merge(a,b,i,i+s-1,n-1);
else
{
for(int j=i;j<=n-1;j++)
b[j]=a[j];
}
}
void mergesort(int a[],int n)
{
int *b =new int [n];
int s=1;
while(s<n)
{
mergepass(a,b,s,n);
s=s+s;
mergepass(b,a,s,n);
s=s+s;
}
}
int main()
{
int a[10]={3,5,2,7,8,1,9,0,13,41};
int b[8]={7,5,4,3,6,12,2,1};
mergesort(a,10);
mergesort(b,8);
for(int i=0;i<10;i++)
cout<<a[i]<<" ";
cout<<endl;
for(int j=0;j<8;j++)
cout<<b[j]<<" ";
cout<<endl;
return 0;
}
快速排序
#include <iostream>
using namespace std;
int Partition(int a[],int l,int r)
{
int x=a[l];
int i=l+1,j=r;
while(i<=j)
{
while(a[i]<=x)
i++;
while(a[j]>x)
j--;
if(i>j)
break;
int t=a[i];
a[i]=a[j];
a[j]=t;
}
a[l]=a[j];
a[j]=x;
return j;
}
void quicksort(int a[],int l,int r)
{
if(l<r){
int q=Partition(a,l,r);
quicksort(a,l,q-1);
quicksort(a,q+1,r);
}
}
int main()
{
int a[10]={3,5,2,7,8,1,9,0,13,41};
int b[8]={7,5,4,3,6,12,2,1};
quicksort(a,0,9);
quicksort(b,0,7);
for(int i=0;i<10;i++)
cout<<a[i]<<" ";
cout<<endl;
for(int j=0;j<8;j++)
cout<<b[j]<<" ";
cout<<endl;
return 0;
}
二分查找
#include <iostream>
using namespace std;
int binarysearch(int a[],int n,int x)
{
int l=0,r=n-1;
while(l<=r)
{
int m=(l+r)/2;
if(x==a[m])
return m;
if(x>a[m])
l=m+1;
else
r=m-1;
}
return -1;
}
int main()
{
int a[8]={1,3,4,5,6,7,8,9};
int x=binarysearch(a,8,5);
cout<<x<<endl;
return 0;
}
插入排序
#include <iostream>
using namespace std;
void InsertSort(int a[],int n)
{
for(int i=0;i<n;i++)
{
int x=a[i];
int j=i-1;
while(j>=0&&a[j]>x)
{
a[j+1]=a[j];
j--;
}
a[++j]=x;
}
}
int main()
{
int a[10]={3,5,2,7,8,1,9,0,13,41};
InsertSort(a,10);
for(int i=0;i<10;i++)
cout<<a[i]<<" ";
cout<<endl;
return 0;
}