ACM算法一递归

视频参考网址:https://www.bilibili.com/video/BV1nx411D7Lm

1. 从数组中找出最大值

#include<iostream>
using namespace std;

int FindMax(int arr[],int L,int R)
{
	if(L==R)
		return arr[L];
	if(L<R)
	{
		int a=arr[L];
		int b=FindMax(arr,L+1,R);
		if(a>b)
			return a;
		else
			return b;
	}	
}
int main()
{
	int arr[]={7,6,3,10,9,8,2,1,5,4};
	int mx=FindMax(arr,0,9);
	cout<<mx<<endl;
}

2.数组求和

#include<iostream>
using namespace std;

int my_sum(int arr[],int L,int R )
{
	if(L==R)
		return arr[L];
	return arr[L]+my_sum(arr,L+1,R);
}
int main()
{
	int arr[]={2,6,5,8,0};
	int sum=my_sum(arr,0,4);
	cout<<sum<<endl;
}

3. 冒泡排序

#include<iostream>
#include<stdio.h>
using namespace std;

void bubble(int a[],int L,int R)
{
	if(L<R)
	{
		for(int i=L;i<R;i++)
		{
			if(a[i]>a[i+1])
			{
				int temp=a[i];
				a[i]=a[i+1];
				a[i+1]=temp;
			}
		}
		bubble(a,L,R-1);
	}
	
}
int main()
{
	int arr[]={8,6,5,9,10,2,1,3,4,7};
	bubble(arr,0,9);
	for(int i=0;i<=9;i++)
		cout<<arr[i]<<" ";
}

4.求最大公约数(辗转相除法)

#include<iostream>
#include<stdio.h>
using namespace std;

int gcd(int a,int b)
{
	int r=a%b;
	if(r==0)
			return b;
	else
		return gcd(b,r);//------转化为b,r的最大公约数-------//
}
int main()
{
	int a,b;
	cin>>a>>b;
	cout<<gcd(a,b)<<endl;
	return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值