用java寫遞歸函數找出數組的最大值

WBOY
發布: 2024-01-13 19:06:23
轉載
985 人瀏覽過

怎樣用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
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!