Java Reference
In-Depth Information
into ascending
// order.
for (int pass = 0; pass < x.length-1; pass++)
for (int i = x.length-1; i > pass; i--)
if (x[i] < x[pass])
{
int temp = x[i];
x[i] = x[pass];
x[pass] = temp;
}
}
}
Listing 3-36 ' s application simulates Lotto 6/49, one of Canada's national lottery
games. The rnd() helper method returns a randomly chosen integer between 0 and
limit -1.Anassertionstatementverifiesthepreconditionthat limit 'svaluemustbe
2 or higher.
Note The sort() helper method sorts (orders) the selectedNumbers array's
integersintoascendingorderbyimplementingan algorithm (arecipeforaccomplish-
ing some task) called Bubble Sort .
BubbleSortworksbymakingmultiplepassesoverthearray.Duringeachpass,various
comparisonsandswapsensurethattheextsmallestelementvalue“bubbles”towardthe
top of the array, which would be the element at index 0.
Bubble Sort is not efficient, but is more than adequate for sorting a six-element
array. Although I could have used one of the efficient sort() methods located
in the java.util package's Arrays class (for example, Ar-
rays.sort(selectedNumbers); accomplishes the same objective as Listing
3-36 ' s sort(selectedNumbers); method call, but does so more efficiently), I
chosetouseBubbleSortbecauseIprefertowaituntil Chapter5 beforegettingintothe
Arrays class.
Postconditions
A postcondition is something that must be true after a method successfully completes.
Assertionstatementsareoftenusedtosatisfyahelpermethod'spostconditionsbycheck-
ing that its result is legal. Listing 3-37 provides an example.
Search WWH ::




Custom Search