Java Reference
In-Depth Information
Let's trace the execution of the following statement:
System.out.println(largest(list, 0, 3));
Here, upperIndex = 3 and the list has four elements. Figure 13-4 traces the execution of
largest(list, 0, 3) .
largest(list,0,3)
return 12
lowerIndex
0
upperIndex
3
max
max
12
because lowerIndex != upperIndex
max = largest(list,1,3)
because list[0] < max
return max
largest(list,1,3)
return 12
lowerIndex
1
upperIndex
3
max
because lowerIndex != upperIndex
max = largest(list,2,3)
max
12
because list[1] < max
return max
largest(list,2,3)
lowerIndex
2
upperIndex
3
max
return 12
because lowerIndex != upperIndex
max = largest(list,3,3)
max
8
because list[2] > max
return list[2]
largest(list,3,3)
lowerIndex
3
upperIndex
3
max
because lowerIndex == upperIndex
return list[3]
return 8
FIGURE 13-4 Execution of largest(list, 0, 3)
The value returned by the expression largest(list, 0, 3) is 12 , which is the largest
element in list .
The following Java program uses the method largest to determine the largest element
in the list:
//Recursion: Largest Element in an Array
import java.io.*;
public class
LargestElementInAnArray
{
public static void main(String[] args)
{
int []
intArray = {23, 43, 35, 38, 67, 12, 76,
10, 34, 8};
Search WWH ::




Custom Search