Java Reference
In-Depth Information
5. Determining the largest element in the array: We now discuss an
algorithm to find the largest element in an array—that is, the array
element with the largest value. However, the user is typically more
interested in determining the location of the largest element in the array.
Of course, if you know the location (the index of the largest element in
the array), you can easily determine the value of the largest element in
the array. Let's describe the algorithm to determine the index of the
largest element in an array—in particular, the index of the largest sale
amount in the array sales .
We assume that maxIndex will contain the index of the largest element in the array
sales . The general algorithm is as follows. Initially, we assume that the first element in
the list is the largest element, so maxIndex is initialized to 0 . We then compare the
element to which maxIndex points with every element in the list. Whenever we find an
element in the array larger than the element to which maxIndex points, we update
maxIndex so that it stores the index of the new larger element. The code to implement
this algorithm is as follows:
maxIndex = 0;
for ( int index = 1; index < sales.length; index++)
if (sales[maxIndex] < sales[index])
maxIndex = index;
largestSale = sales[maxIndex];
9
The way this code works can be demonstrated with an example. Suppose the array
sales is as given in Figure 9-6, and we want to determine the largest element in
the array.
[7] [8] [9]
12.50 8.35 19.60 25.00 14.00 39.43 35.90 98.23 66.65 35.64
s
[0]
[1]
[2]
[3]
[4]
[5]
[
]
FIGURE 9-6 Array sales
Search WWH ::




Custom Search