Java Reference
In-Depth Information
System.out.println("The largest element in intArray: "
+ largest(intArray, 0, intArray.length - 1));
}
public static int largest( int [] list,
int lowerIndex, int upperIndex)
{
int max;
if (lowerIndex == upperIndex)
return list[lowerIndex];
else
{
max = largest(list, lowerIndex + 1, upperIndex);
if (list[lowerIndex] >= max)
return list[lowerIndex];
else
return max;
}
}
}
Sample Run:
The largest element in intArray: 76
EXAMPLE 13-2 FIBONACCI NUMBER
In Chapter 5, we designed a program to determine the desired Fibonacci number. In this
example, we write a recursive method, rFibNum , to determine the desired Fibonacci
number. The method rFibNum takes as parameters three numbers representing the first
two numbers of the Fibonacci sequence and a number n, the desired nth Fibonacci
number. The method rFibNum returns the nth Fibonacci number in the sequence.
Recall that the third Fibonacci number is the sum of the first two Fibonacci numbers.
The fourth Fibonacci number in a sequence is the sum of the second and third Fibonacci
numbers. Therefore, to calculate the fourth Fibonacci number, we add the second
Fibonacci number and the third Fibonacci number (which itself is the sum of the first
two Fibonacci numbers). The following recursive algorithm calculates the nth Fibonacci
number, where a denotes the first Fibonacci number, b the second Fibonacci number,
and n the nth Fibonacci number:
1
3
8
<
:
a
if n ¼ 1
rFibNum ð a ; b ; n Þ¼
b
if n ¼ 2
ð 13-3 Þ
rFibNum ð a ; b ; n 1 Þþ rFibNum ð a ; b ; n 2 Þ
if n > 2 :
 
Search WWH ::




Custom Search