首页  >  文章  >  电脑教程  >  用java编写递归函数查找数组的最大值

用java编写递归函数查找数组的最大值

WBOY
WBOY转载
2024-01-13 19:06:23965浏览

用java编写递归函数查找数组的最大值

public static void main(String[] rags){

int [] aim = new int[100];

int point = 0;

//....这里初始化数组

int max = aim[0];

max = getMax(max,point,aim);

//...其他处理

}

//递归方法

public int getMax(int max,int point,int[] aim){

if(point==aim.length) //临界值

return max;

//未达到临界值时,取max值,并进行递归

max = max >= aim[point] ? max : aim[point];

return getMax(max,point+1,aim);

}

java二分法查找的递归算法怎么实现

public class 二分法递归查找 {

public static void main(String[] args) {

//定义数组,注意,二分查找数组必须是有序的数组!

int[] arr = { 1, 3, 5, 7, 9, 11, 13, 15, 17 };

//接受查找后的返回值:索引值,如果没有则是-1;

//测试查找元素:9

int a=binary(arr, 9, 0, arr.length - 1);

System.out.println("被查找数字索引位置在:"+a);

}

//参数列表依次为:被查找的数组,查找的数字,头索引,尾索引!

public static int binary(int[] arr, int key, int star, int end)// 递归

{

//每次进来创建,中间索引值!

int mid = (star + end) / 2;

//如果被查找数小于头,或者尾,或者头索引大于尾索引,则说明无该数,返回-1;

if (key arr[end] || star > end) {

return -1;

}

//如果中间值小于被查找数,则重新定义头索引移至中间+1位置,筛选掉一半数字!

if (arr[mid]

//开始递归!

return binary(arr, key, mid + 1, end);

//否则如果中间值大于被查找数,则重新尾索引移至中间-1位置,筛选掉一半数字!

} else if (arr[mid] > key) {

//开始递归!

return binary(arr,key, star, mid - 1);

} else {

//否者就是找到了,返回该索引!

return mid;

}

}

}

用java编写递归函数查找数组的最大值

java的递归是如何执行的顺序是如何执行的

factest(8)进入factest函数,if(n==1) return 1; // 不成立,执行else else return n*factest(n-1); // 返回值为8*factest(7)

factest(7)进入factest函数,if(n==1) return 1; // 不成立,执行else

else return n*factest(n-1); // 返回值为7*factest(6)

……

一直到N=1,此时if(n==1) return 1; // 成立,返回值为1,即1!=1

然后计算出factest(2)返回值为:2*factest(1) = 2

接着继续计算出factest(3)返回值为:3*factest(2) = 6

…… 一直到N=8,得到factest(8) = 8*factest(7) = 40320

JAVA这道题要如何用递归实现呢大神

按照你的要编写的Java递归程序如下:

import java.util.Scanner;

public class GGG {

public static void main(String[] args) {

int N = 0;

Scanner sc=new Scanner(System.in);

int num=sc.nextInt();

for(int n=0;n

N=sc.nextInt();

int a[]=new int[N];

for(int i=0;i

a[i]=sc.nextInt();

}

System.out.print("case "+(n+1)+":");

process(a,0);

System.out.println();

}

}

private static void process(int[] a, int n) {

if(n==0){

if(isPrime(a[n+1]))

System.out.print(1+" ");

else

System.out.print(0+" ");

}else if(n==a.length-1){

if(isPrime(a[n-1]))

System.out.print(1+" ");

else

System.out.print(0+" ");

return;

}else{

if(isPrime(a[n-1])&isPrime(a[n+1]))

System.out.print(2+" ");

else if(isPrime(a[n-1])||isPrime(a[n+1]))

System.out.print(1+" ");

else

System.out.print(0+" ");

}

process(a,n+1);

}

public static boolean isPrime(int num) {

int i;

for(i=2;i

if(num%i==0)

break;

}

if(i==num){

return true;

}

return false;

}

}运行结果:

2

5

5 7 2 9 13

case 1:1 2 1 2 0

3

10 4 5

case 2:0 1 0

以上是用java编写递归函数查找数组的最大值的详细内容。更多信息请关注PHP中文网其他相关文章!

声明:
本文转载于:docexcel.net。如有侵权,请联系admin@php.cn删除