Java Reference
In-Depth Information
5.
Finding the largest element:
Use a variable named
max
to store the largest element.
Initially
max
is
myList[0]
. To find the largest element in the array
myList
, compare
each element with
max
, and update
max
if the element is greater than
max
.
double
max = myList[
0
];
for
(
int
i =
1
; i < myList.length; i++) {
if
(myList[i] > max) max = myList[i];
}
6.
Finding the smallest index of the largest element:
Often you need to locate the largest
element in an array. If an array has multiple elements with the same largest value, find the
smallest index of such an element. Suppose the array
myList
is {
1
,
5
,
3
,
4
,
5
,
5
}. The
largest element is
5
and the smallest index for
5
is
1
. Use a variable named
max
to store
the largest element and a variable named
indexOfMax
to denote the index of the largest
element. Initially
max
is
myList[0]
, and
indexOfMax
is
0
. Compare each element in
myList
with
max
, and update
max
and
indexOfMax
if the element is greater than
max
.
double
max = myList[
0
];
int
indexOfMax =
0
;
for
(
int
i =
1
; i < myList.length; i++) {
if
(myList[i] > max) {
max = myList[i];
indexOfMax = i;
}
}
7.
Random shuffling:
In many applications, you need to randomly reorder the elements
in an array. This is called
shuffling
. To accomplish this, for each element
myList[i]
,
randomly generate an index
j
and swap
myList[i]
with
myList[j]
, as follows:
Random shuffling
VideoNote
Random shuffling
myList
for
(
int
i = myList.length - 1; i >
0
; i--) {
// Generate an index j randomly with 0 <= j <= i
int
j = (
int
)(Math.random()
* (i +
1
));
i
[0]
.
[1]
.
A random index [j]
// Swap myList[i] with myList[j]
double
temp = myList[i];
myList[i] = myList[j];
myList[j] = temp;
}
swap
[
i
]
8.
Shifting elements:
Sometimes you need to shift the elements left or right. Here is an
example of shifting the elements one position to the left and filling the last element with
the first element:
double
temp = myList[
0
];
// Retain the first element
myList
// Shift elements left
for
(
int
i =
1
; i < myList.length; i++) {
myList[i -
1
] = myList[i];
}
// Move the first element to fill in the last position
myList[myList.length -
1
] = temp;
9.
Simplifying coding:
Arrays can be used to greatly simplify coding for certain tasks. For
example, suppose you wish to obtain the English name of a given month by its number.
If the month names are stored in an array, the month name for a given month can be
Search WWH ::
Custom Search