算法实训
一.
//p116 递归实现快速排序
#include<stdio.h>
#include<stdlib.h>
#include<time.h>
int r[20001];
int main()
{
int i,n,t;
void qk(int m1,int m2);
t=time(0)%1000;
srand(t); //输出随机数
printf(" input n:");
scanf("%d",&n);
printf(" 参与排序的%d个整数为:\n",n);
for(i=1;i<=n;i++)
{
r[i]=rand()%(4*n)+10;
printf("%d “,r[i]); //输出格式有空格,记得在%d后面空格
}
qk(1,n);
printf(” \n 以上%d个整数从小到大排序为:\n",n);
for(i=1;i<=n;i++)
printf("%d “,r[i]); //空格
printf(”\n");
return 0;
}
void qk(int m1,int m2)
{
int i,j;
if(m1<m2)
{
i=m1;j=m2;r[0]=r[i];
while(i!=j)
{
while(r[j]>=r[0]&&j>i)
j=j-1;
if(i<j){r[i]=r[j];i=i+1;}
while(r[i]<=r[0]&&j>i)
i=i+1;
if(i<j){r[j]=r[i];j=j-1;}
}
r[i]=r[0];
qk(m1,i-1);qk(i+1,m2);
}
return ;
}
二.
//二分查找
#include
using namespace std;
int BinarySearch(int a[],int size,int p){
int l = 0,r = size-1;
while(l<=r){
int mid = l + (r-l)/2;
if(p == a[mid])
return mid;
if(p > a[mid]){
l = mid+1;
}else{
r = mid-1;
}
}
return -1;
}
int LowerBound(int a[],int size,int p){
int l = 0,r = size-1;
int LastPos = -1;
while(l<=r){
int mid = l + (r-l)/2;
if(a[mid] >= p){
r = mid - 1;
}else{
LastPos = mid;
l = mid + 1;
}
}
return LastPos;
}
int main(){
int a[8] = {4,10,15,25,45,48,78,145};
cout << BinarySearch(a,8,45) << endl;
cout << LowerBound(a,8,45) << endl;
return 0;
}
三.
//0-1背包问题
#include<stdio.h>
#define N 100
void main()
{
float p[N],w[N],x[N],c,cw,s,h;
int i,j,n;
printf("\n input n: “); //物品个数
scanf(”%d",&n);
printf(“input c: “); //背包的重量
scanf(”%f”,&c);
for(i=1;i<=n;i++)
{
printf(“input w%d,p%d: “,i,i); //放的物品的重量和物品的价值
scanf(”%f%f”,&w[i],&p[i]);
}
for(i=1;i<=n-1;i++) //对n个物品按单位重量的效益从大到小排序
for(j=i+1;j<=n;j++)
if(p[i]/w[i]<p[j]/w[j])
{
h=p[i];
p[i]=p[j];
p[j]=h;
h=w[i];
w[i]=w[j];
w[j]=h;
}
cw=c;
s=0;
for(i=1;i<=n;i++) //若w[i]<=cw,整体装入
{
if(w[i]>cw)
break;
x[i]=1.0;
cw=cw-w[i];
s=s+p[i];
}
x[i]=(float)(cw/w[i]);
s=s+p[i]*x[i];
printf("装包: ");
for(i=1;i<=n;i++)
if(x[i]<1)
break;
else
printf("\n装入的重量为%5.lf效益为%5.lf的物品。",w[i],p[i]);
if(x[i]>0 && x[i]<1)
printf("\n装入的重量为%5.lf效益为%5.lf的物品百分之%5.lf。",w[i],p[i],x[i]*100);
printf("\n所得最大效益为:%7.lf",s);
}